0% found this document useful (0 votes)
25 views

OOP Through Java Unit-3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

OOP Through Java Unit-3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT III

Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract class.
Interfaces, creating the packages, using packages, importance of CLASSPATH and java.lang package.
Exception handling, importance of try, catch, throw, throws and finally block, user defined exceptions.

Inheritance
 The process by which one class acquires the properties i.e., variables, methods, constructors,
sub classes etc. from another class is called as inheritance (base class  derived class)

 It is a process of creating a new class from the existing class.

Points to be remembered:
 Inheritance is the most important and useful feature of OOP.
 The existing class is known as parent class or base class or super class.
 The new class is known as child class or derived class or sub class.
 The Parent class is the class which provides features to another class.
 The Child class is the class which receives features from another class.
 It can be done by the extends keyword.
 It follows IS-A relationship.
Uses / Advantages:
 It allows us to reuse of code to improve the performance(Code Reusability).
 For Method Overriding (to achieve runtime polymorphism).
Disadvantages:
 Complicated.
 Invoking methods creates overhead to the compiler.
Syntax:
class <ChildClassName> extends <ParentClassName>
{
//Implementation of child class
}

As displayed in the figure, Programmer is the


subclass and Employee is the superclass. The
relationship between the two classes
is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

1
Types of Inheritance:
 There are 3 types of inheritances in Java
 Single inheritance
 Multi-level inheritance
 Hierarchical inheritance
Note:
Multiple inheritance and Hybrid inheritance can’t achieve directly but can achieve through
interface.
1.Single Inheritance:
It is a process of creating / deriving a class from single base class is known as Single Inheritance.

 The class A serves as a base class for the derived class B

class A{ class SingleInheritance


int a=10;
{
void show(){
public static void main(String a[])
System.out.print(a);
{
}
B b = new B();
}
b.show();
class B extends A{
b.display();
int b=20;
b.sum();
void display(){
}
System.out.print(b);
}
}
Output:
void sum(){
10 20 30
System.out.print(a+b);
2
}
}

2.Multilevel inheritance:
It is a process of creating / deriving a class from already derived class is known as Multilevel
Inheritance.

 The class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C.
 C class can directly access the variables and methods of A, B and C.

3
class MultiLevelInheritence{
Example
public static void main(String args[]){
class A{ C obj = new C();
int a=10; System.out.println(“C Class Variable=”+obj.c);
void dispa(){ obj.dispc();
System.out.println(“A Class”); System.out.println(“B Class Variable=”+ obj.b);
} obj.dispb();
class B extends A{ System.out.println(“A Class Variable=”+ obj.a);
int b=20; obj.dispa();
void dispb(){ }
System.out.println(“B Class”); }
} Output:
class C extends B{ C Class Variable=30
int c=30; C Class
B Class Variable=20
void dispc(){ B Class
System.out.println(“C Class”); A Class Variable=10
A Class
}

3.Hierarchical Inheritance:
It is a process of creating / deriving Multiple classes from single base class is known as
Hierarchical Inheritance.

 The class A serves as a base class for the derived class B, C and D.
 Using B Class Object, we can’t access C class properties and D class properties.
 Using C Class Object, we can’t access B class properties and D class properties.
4
 Using D Class Object, we can’t access B class properties and C class properties.

Hybrid Inheritance
 It is a combination of more than one type of inheritance
 If the combination consists of multiple inheritance, not possible to implement

B C

× Invalid  Valid

5
Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
(or)
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Imp Points:
 Method overriding is used for runtime polymorphism.
 Base class and Derived class should have the same method name (preference given to sub
class)
 Both the methods should have same return type, scope and signature (no., order of
parameters & Type of parameters)
 Private, Static and Final methods can’t be override.

Example:

class Parent{
void display()
{
System.out.println(“PARENT CLASS”);
}
}
class Child extends Parent{
void display()
{
super.display();
System.out.println(“CHILD CLASS”);
}
}
class Override
{
public static void main(String args[])
{
Child c = new Child();
c.display();
}}

Output:
PARENT CLASS
CHILD CLASS

6
 Implementing the same thing with different ways i.e., Polymorphism

S. No Method Overloading Method Overriding

1 Can be achieved compile time Can be achieved run time polymorphism


polymorphism
2 Static binding / Early binding Dynamic binding / Late binding

3 Implemented within a single class Implemented in two different classes


4 No need of inheritance to achieve With the help of inheritance to achieve
this this
5 Used to increase readability of Used to provide different implementation
program of super class method
6 Method name should be same Method name should be same

7 Signature must be different Signature must be same


8 Return type can be same or different Return type should be same
9 Static methods can be overloaded Static methods can’t be overridden

10 Private methods can be overloaded Private methods can’t be overridden


11 Final methods can be overloaded Final methods can’t be overridden

Super Keyword
The super keyword in java is a reference variable which is used to refer immediate parent class
object.

Uses of Super keyword:


 It can be used to access the variables, methods, constructors of base class into derived
class.
 It is used to eliminate the confusion between superclass and subclass that have the methods
and variables with the same name.
 Super() can be used to invoke immediagte parent class constructor.
 Super can be used to refer immediate parent class instance variable.
super.variablename
 Super can be used to invoke immediate parent class method.
Super.methodname()

7
Example - 1:
class Parent
{
int a=40;
void display()
{
System.out.println(“PARENT CLASS”);
}
}

class Child extends Parent


{
int a=30;
void display()
{
System.out.println (“CHILD CLASS”);
System.out.println (a);
System.out.println(super.a);
super.display();
}
}
class SuperDemo
{
public static void main(String args[])
{
Child c = new Child();
c.display();
}
}

Output:
CHILD CLASS
30
40
PARENT CLASS

8
Final Keyword
In Java, the final keyword is used to denote constants. It can be used with variables, methods,
and classes. It is used to restrict a user in java.
Once any entity (variable, method or class) is declared final, it can be assigned only once. That is,
 The final variable cannot be reinitialized with another value
 The final method cannot be overridden
 The final class cannot be extended

final variable: If a variable can be defined with final then that variable value cannot be changed
during the scope of program i.e., constant value.

Example-:
class Sample{
final int a=10;
Sample()
{
a=20;
}
}
class Test{
public static void main(String args[])
{
Sample obj=new Sample();
}
}
Output:
can’t assign a value to final variable a

final method: If a method can be defined with final then that method cannot be overridden

Example: class FinalTest{


class Parent{ public static void main(String args[]){
final void m1() Child obj=new Child();
{ obj.m1();
System.out.println(“Parent Class”); }
} }
} Output:
class Child extends Parent{ m1() in Child can’t override m1() in
void m1(){
Parent
System.out.println(“Child Class”);
}
}

9
final class: If a class can be defined with final then that class cannot be inherited.
Example: class FinalTest{
public static void main(String args[]){
final class Parent{
void m1()
Child obj=new Child();
{
obj.m1();
System.out.println(“Parent Class”);
}
}
}
}
class Child extends Parent{
void m1(){ Output:
System.out.println(“Child Class”); cannot inherit from final Parent
}
}

Abstract Keyword
Abstraction in Java: Abstraction is a process of hiding the implementation details and showing
only functionality to the user.

There are two ways to achieve abstraction in java


 Abstract class
 Interface
Abstract class
 A class which is declared with the abstract keyword is known as an abstract class in Java.
 It can have Variables, abstract(method without body) and non-abstract methods (method
with the body).
 It can have constructors and static methods also.
 An Abstract class cannot be instantiated(object creation).

 If a class contains complete definition for all methods then that is called concrete class

Abstract Method

 If a method is declared with abstract keyword then it is called as abstract method.


 abstract method contains only declarations i.e., it doesn’t provide implementation
of a method.
 If a class is having atleast one abstract method then class is called abstract class & it may
also have normal methods.
 Implementation of abstract method can be written in derived class only

10
Example:

abstract class A
{
Output:
abstract void display();
} Abstract Method in A
class B extends A{
void display()
{
System.out.println(“Abstract Method in A”);
}
}
class AbstractDemo{
public static void main(String args[]){
B b = new B();
b.display();
}
}

Abstract Class vs Concrete Class vs Interface:


S. No Abstract Class Concrete Class

1 It is declared using abstract modifier No need of access modifier

2 It is not possible to create object for abstract We can create object for concrete class
class

3 Abstract class contains abstract Concrete class contains only concrete methods
methods and concrete methods also but not abstract methods

4 Abstract class can’t be declared as final Concrete class can be declared as final

S. No Abstract Class Interface

2 We can’t implement multiple We can implement multiple inheritance


inheritance

3 Every method present in abstract class need not Every method present in interface is by default
be public & abstract public & abstract

4 Every variable present in abstract class need not Every variable present in interface is always
be public, static & final public, static & final
Interfaces
• An interface in java is a blueprint of a class.

• Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body)
• An interface cannot be instantiated.
• To implement interface in a class, use implements keyword.
• A class can implement any number of interfaces.
• By default, each and every method in the interface is a public abstract.
• By default every variable in interface acts like public static final.
• We cannot create constructors in interface.
• We can use static method in interface.
• To declare an interface, use interface keyword
Advantages:
 Interface is used to implement multiple inheritance in java.
 It provides fully abstraction in java.
Syntax:
interface interface_name {
// declare fields // By default public static final
// declare methods // By default public abstract
}
Multiple Inheritance:

1)

implements

2)

implements extends

Example:
interface A{
int a=10;
void sum();
}
interface B{
int b=20;
}
class C implements A,B{
public void sum(){
System.out.println(“sum=”+(a+b))
}
}
class Test{
public static void main(String args[]){
C obj = new C();
obj.sum();
}
}

Output:
Sum=30
Packages
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two forms:

1. built-in package

2. user-defined package.

 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantages of Java Package

1) It provides code-reusablility.

2) It offers Modularity.

3) It removes naming collision.

14
Simple example of java package
The package keyword is used to create a package in java.

//save as Test.java
package mypack;
public class Test
{
public void add( ) {
int a=20,b=40;
System.out.println("sum="+(a+b));
}
}

 First create a folder with the name of the package.

 Create a java file in the newly created folder.

 In this java file, specify the package name with the help of the package keyword.

 Now compile the program.


Accessing/importing Package:

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

 If we use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.

import mypack.*;
class Main
{
public static void main(String[]args)
{
Test t=new Test();
t.add();
}}

15
Output:
Sum=60

2) Using packagename.classname:

 If we import packagename.classname then only declared class of this package will be


accessible.

import mypack.Test;
class Main
{
public static void main(String[]args)
{
Test t=new Test();
t.add();
}}

Output:
Sum=60

3) Using fully qualified name:

 If we use fully qualified name then only declared class of this package will be accessible..

class Main{
public static void main(String[]args)
{
mypack.Test t=new mypack.Test();
t.add();
}}

Output:
Sum=60

Subpackage in java
 Package inside the package is called the subpackage. It should be created to
categorize the package further.

16
Exception Handling
 Exception is an unwanted event that interrupts the normal flow of the program (or) runtime
error which will occurs during program execution
 If any error occurred, the remaining code will not execute and terminate the program
abnormally
 Exception handling allows us to handle the runtime errors caused by exceptions
 Used to raise an exception, handle an exception and avoiding abnormal termination of a
program
 We use 5 keywords in this i.e., try, catch, throw, throws, finally
 Exceptions are handled with the help of try and catch blocks
 Try and catch blocks are interrelated i.e., without try we can’t use catch and vice versa.
Hierarchy of Java Exception classes:

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

17
Types of Java Exceptions:
There are mainly two types of exceptions:

1. Checked Exception

2. Unchecked Exception
1. Checked (Compile Time) Exception:
 Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler.
 Ex: IOException, SQLException etc...
2. Unchecked (Run Time)Exception:
 Unchecked exceptions are not checked at compile-time, but they are checked at runtime
 Ex: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException etc…

Java Exception Keywords:

Keyword Description

Try "try" keyword is used to specify a block where we should place exception code
The try block must be followed by either catch or finally. It means, we can't use try block
alone
Catch "catch" block is used to handle the exception
It must be preceded by try block which means we can't use catch block alone. It can be
followed by finally block later

Finally It is optional."finally" block is used to execute the important code


of the programIt is executed whether an exception is handled or not

Throw "throw" keyword is used to throw an exception implicitly or explicitly from a method or
any block of code.

Throws "throws" keyword is used to declare exceptions. It doesn't throw an exception


It specifies that there may occur an exception in the method & always used with method
signature.

18
Built-in Exceptions:
1. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
2. FileNotFoundException
This Exception is raised when a file is not accessible or does not open
3. IOException
It is raised when an input-output operation failed or interrupted
4. InterruptedException
It is raised when a thread is waiting, sleeping or doing some processing and it is interrupted
5. ArithmeticException
It is raised when an exception has occurred in an arithmetic operation such as division by zero.
6. ArrayIndexOutOfBoundsException
It is raised when an array has been accessed with an illegal index. The index is either negative
or greater than or equal to the size of the array
7. NullPointerException
It is raised when referring to the members of a null object. Null represents nothing
8. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
9. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
10. NoSuchMethodException
It is thrown when accessing a method which is not found.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or greater than
the size ofthe string

Java try-catch block:


 Try and catch statements are used to catch and handle exceptions in java.
 Statements that can raise exceptions are written inside the try block and the statements that handle
the exception are written inside catch block.
 The try block must be followed by either catch or finally. It means, we can't use try block
alone

19
Syntax:
Syntax:
try
try
{
{
//code that may throw an exception
//code that may throw an exception
}
}
finally
catch (Exception_class_Name ref)
{
{
// important code
// handle the exception
}
}

Example-1:
public class ExceptionHandlingDemo {

public static void main(String[] args) {


int a=10,b=5,c=5,x;
x=a/(b-c);
System.out.println(x);
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

Example-2:
public class ExceptionHandlingDemo1 {
public static void main(String[] args) {
int x,y;
int a=10,b=5,c=5;
try
{
x=a/(b-c);
System.out.println(x);
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero Error");
}
System.out.println("After Catch Block");
}
}
Output:
Division by zero error
After Try-Catch Block

20
Types of Unchecked (Run Time)Exceptions:
1. ArithmeticException  divide by zero
2. NullPointerException  sring str = null;
System.out.println(str.length()); ˟
3. NumberFormatException  sring str = “hello”;
int num = Integer.ParseInt(str); ˟
4. ArrayIndexOutOfBoundsException  int a[] = new int[5];
a[8] = 20; ˟

Java Multi-Catch block


 A try block can be followed by one or more catch blocks.

 Each catch block must contain a different exception handler.

 So, if you have to perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
Points to remember:
o At a time only one exception occurs and at a time only one catch block is executed.

Example:
class multitrydemo
{
public static void main(String args[]) {
try
{
int a=10,b=5;
int c=a/b;
int d[]={0,1};
System.out.println(d[10]);
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero error”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Index out of bound error”);
}}}
OUT-PUT:
Index out of bound error
After the catch statement

21
Usage of Java finally

 In Java, the finally block is always executed no matter whether there is an exception or not.

 The finally block is optional. And, for each try block, there can be only one finally block.

Syntax: Syntax:
try
try
{
{
//code that may throw an exception
//code that may throw an exception
}
}
catch (Exception_class_Name ref)
finally
{
{
// handle the exception
// important code
}
}
finally
{
// important code
}

Example: When an exception does not occur

public class FinallyDemo


{
public static void main(String[] args)
{
int x,y;
int a=10,b=5,c=5;
try
{
y=a/(b+c);
System.out.println(y);
}
finally
{
System.out.println("This is finally block");
}
}}
Output:
1
This is finally block

22
Java throw keyword
(or)
User-defined Exception
 The Java throw keyword is used to explicitly throw a single exception.

 When we throw an exception, the flow of the program moves from the try block to
the catch block.
 We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception. 

 Java provides us facility to create our own exceptions which are basically derived classes
of Exception class.
For example MyException in below code extends the Exception class.

Syntax
throw new exception_class("error message");
Example-1:
import java.lang.*;
class MyException extends Exception{
public MyException(String s){
// Call constructor of parent Exception
super(s);
}
}
class ThrowExcep
{
public static void main (String[] args) {
try
{
throw new ArithmeticException("My Own Exception");

}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
My Own Exception

23
Java throws Keyword
 throws is a keyword in Java that is used in the declaration of a method to indicate that this
method might throw one of the listed type exceptions.
 The caller to these methods has to handle the exception using a try-catch block.

Syntax

type method_name(parameters) throws exception_list

Example-1:

class ThrowsDemo {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Java Programming");
}
}

Output:
ThrowsDemo.java:4: error: unreported exception InterruptedException; must be caught or
declared to be thrown
Thread.sleep(10000);

Example – 2:

class ThrowsDemo {
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Java Programming");
}
}

Output:
Java Programming

24
Assertion
 Assertion is a statement in java. It can be used to test your assumptions about the program.
 While executing assertion, it is believed to be true.
 If it fails, JVM will throw an error named AssertionError. It is mainly used for testing
purpose.
Advantage of Assertion:
 It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:


There are two ways to use assertion. First way is:
assert expression;
and second way is:
assert expression1 : expression2;

Simple Example of Assertion in java:


import java.util.Scanner;
class AssertionExample
{
public static void main( String args[] )
{
Scanner s = new Scanner( System.in );
System.out.print("Enter value ");
int value = s.nextInt();
assert value<=18:" Not valid";
System.out.println("value is "+value);
}
}
Output: Enter value 34
Exception in thread "main" java.lang.AssertionError: Not valid

25

You might also like