Inheritance
Inheritance
Unit-3: Inheritance: Inheritance basics, using super and final, method overriding, dynamic method
dispatch, Abstract Class, Interface: variables and extending Interfaces, Package: Creating and
importing packages, Package access protection, Exception Handling: Exception handling
fundamentals, Exception types, Uncaught Exceptions Using try and catch, multiple catch clauses,
nested try statements, throw, Java’s built-in exceptions.
Inheritance: Inheritance is a mechanism in which one class can acquire the property of another
class. Inheritance is a mechanism in which one object acquires all the properties and behaviors of
a parent object. The idea behind inheritance is to create new classes that are built upon existing
classes.
The new class that is created is known as subclass (child or derived class) and the existing class
from where the child class is derived is known as superclass (parent or base class).
Through inheritance, a subclass can access members of its superclass.
Why inheritance?
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Single Inheritance: In this a sub-class is derived from only one super class or when a class inherits
another class, it is known as a single inheritance. . It is also known as simple inheritance.
inherits
inherits
inherits
Class Abc2
Derived Class
Hierarchical inheritance: If a number of classes are derived from a single base class is called
hierarchical inheritance. It allows multiple classes to share common properties and behavior
defined in the superclass.
Java doesn't support multiple inheritance to avoid the 'diamond problem', where ambiguity
arises when a class inherits from two classes with the same method names. Instead, Java uses
interfaces to achieve similar functionality while maintaining clarity and simplicity.
Class Abc1
Single inheritance Heirarchical
Inheritace
Class Abc2 Class Abc3 Class Abc4
The extends keyword indicates that we are making a new class that derives from an existing
class. The meaning of “extends” is to increase the functionality.
e.g.
class Abc
{
//Data members
//member function
}
class Sub extends Abc
{
//Data members
//member function
}
class Exam
{
public static void main(String r[])
{
Calc1ob=new Calc1();
ob.add(10,30);
ob.sub(34,9);
ob.multiply(9,7);
}
}
class Abc1 extends Abc //intermediate base class and derived class
{
void disp1()
{
System.out.println(“class Abc1 method”);
}
}
Output:
Method of Class A
Method of Class B
Method of Class A
Method of Class C
Method of Class A
class Test
{
public static void main(String r[])
{
Abc1 ob1=new Abc1();
Abc1 ob2=new Abc1(10);
Abc1 ob3=new Abc1(10,20,30);
ob1.disp1();
ob1.disp();
ob2.disp1();
ob3.disp1();
}
}
*In the above program class derived from Abc is not implemented as efficiently or robustly as
they could have been. The constructor Abc(), Abc(int i) explicitly initializes a,b. Not only this
duplicate code found in superclass, which is inefficient but subclass must be granted access to
these members.
Syntax
super(); // call the superclass constructor
super.methodName(); //call superclass method
super.datamember; //superclass data member
c=k;
}
void disp1()
{
System.out.println("\na="+a+”\nb=”+b+”\nc=”+c);
}
}
class Test
{
public static void main(String r[])
{
Abc1 ob1=new Abc1();
Abc1 ob2=new Abc1(10);
Abc1 ob3=new Abc1(10,20,30);
ob1.disp1();
ob1.disp();
ob2.disp1();
ob3.disp1();
}
}
2.To access the member of superclass that has been hidden by the member of
subclass:
The super keyword can also be used to invoke parent class data member/method. It should be
used if subclass contains the same data member/method as parent class.
c=k;
}
void disp()
{
super.disp(); //call superclass method
System.out.println("\nc=”+c);
}
}
class Test
{
public static void main(String r[])
{
Abc1 ob1=new Abc1();
Abc1 ob2=new Abc1(10);
Abc1 ob3=new Abc1(10,20,30);
ob1.disp();
ob2.disp();
ob3.disp();
}
}
e.g.
class A
{
A()
{
System.out.println("Class A constructor:”);
}
}
class B extends A
{
B()
{
System.out.println("Class B constructor:”);
}
}
class C extends B
{
C()
{
System.out.println("Class C constructor:”);
}
}
class Test
{
public static void main(String r[])
{
C ob = new C();
}
}
Output:
Class A constructor
Class B constructor
Class C constructor
Method Overriding:
When a method in a subclass has the same name, parameters or signature and return type as a
method in its superclass, then the method in the subclass override the method in the super class.
When a overridden method is called from within a subclass, it will always refer to the version of
the method defined by the subclass. The version of the method defined by the superclass will be
hidden.
Method overriding is used to create a specific implementation of a method that is already present
in the parent class. It also provides multiple implementation of the same method.
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java or If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
Upcasting :
It is a technique in which a superclass reference variable refers to the object of the subclass.
e.g.
class A
{
void disp()
{
System.out.println("class A method”);
}
}
class B extends A
{
void disp() //override disp()
{
System.out.println("class B method”);
}
}
class C extends A
{
void disp() //override disp()
{
System.out.println("class C method”);
}
}
class Test
{
public static void main(String r[])
{
A oa=new A(); //object of class A
B ob=new B(); //object of class B
C oc=new C(); //object of class C
A ref; //reference of A, initially it will point to null
ref=oa; //refer to class A object
ref.disp(); //calling A version
ref=ob; //refer to class B object
ref.disp(); //calling B version
ref=oc; //refer to class C object
ref.disp(); //calling C version
}
}
Any subclass of an abstract class must either implement all of the abstract methods in the
superclass or be itself declared abstract.
Java abstract class is used to provide common method implementation to all the subclasses.
class Test
{
public static void main(String r[])
{
float a=3.4, b=2.6;
Rectangle or=new Rectangle(a,b);
Tritangle ot=new Triangle(a,b);
or.area();
ot.area();
}
}
Interfaces:
Interfaces are similar to classes but they lack instance variables and their methods are declared
without body.
It is a blueprint of a class and contains set of abstract and public methods we want our classes to
implement.
Interfaces are used to achieve abstraction and implement multiple inheritance.
All the methods in interfaces are public and abstract by default (no need to use explicitly abstract
keyword).
Using interface we can specify what a class must do but not how it does it. Once defined any
number of classes can implement an interface. One class can implement any number of
interfaces(multiple inheritance).
Any class implementing an interface will need to provide implementation of methods defined by
interface. Each class is free to determine the details of its own implementation.
Interfaces are designed to support dynamic method resolution at run time. If a method is calles
from one class to another, both classes need to be present at compile time so compiler can check
to ensure that the method signatures are compatible. Interfaces are designed to avoid this problem.
They disconnect the definition of a method from the inheritance hierarchy. Classes are unrelated
in terms of class hierarchy to implement the same interface.
Syntax:
access interface <interface-name>
{
type final-var1=value;
type final-var2=value;
return-type method1(parameter-list);
return-type method2(parameter-list);
}
Where:
access – It is default of public
final-var1, final-var-2 – these are the variables they are implicitly final (cannot be changed).
They must be initialized.
*All methods and variables are implicitly public.
e.g.
interface Shape
{
double PI=3.14;
void area();
}
Implementing interfaces:
To implement an interface, include implements clause in a class definition and then create
methods defined by the interface.
Syntax:
class <class-name> [extends superclass] [implements interface1, interface………]
{
-
-
}
e.g.
interface Shape
{
void area();
}
class Test
{
public static void main(String r[])
{
float a=3.4, b=2.6;
Rectangle or=new Rectangle(4,5);
Triangle ot=new Triangle(a,b);
or.area();
ot.area();
}
}
Interface 1 Interface 2
implements
class
Interface 1 Interface 2
extends
Interface 3
An interface can extend other interface, just a class extend another class. However a class can
extend only one superclass, but an interface can extend any number of interfaces in Java.
Syntax:
interface Abc
{
-
-
}
interface Abc1
{
-
-
}
interface Abc2 extends Abc1,Abc2
{
-
-
}
e.g.
interface Test
{
void disp();
}
interface Test1
{
void disp1();
}
interface Test2 extends Test, Test1
{
void disp2();
}
//class Exam implements methods from interfaces Test, Test1 & Test2
class Exam implements Test2
{
void disp()
{
System.out.println("Method of Test”);
}
void disp1()
{
System.out.println("Method of Test1”);
}
void disp2()
{
System.out.println("Method of Test2”);
}
}
class Main
{
public static void main(String r[])
{
Exam ob=new Exam();
ob.disp();
ob.disp1();
ob.disp2();
}
}
Packages in Java:
A package is a group of similar types of classes, interfaces and sub-packages.
It helps to organize classes into a folder structure and make it easy to locate and use them.
It helps to improve code reusability.
The package is both a naming and a visibility control mechanism. We can define classes inside a
package that are not accessible by code outside that package.
We can also define class members that are only exposed to other members of the same package.
This allows classes to have intimate knowledge to each other, but not expose that knowledge to
the rest of the world.
Advantages of Java Packages:
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Types of Packages:
1. Built-in Packages
2. User defined Packages
Built-in Packages:
The built-in packages are the packages from Java API. The Java API is a library of pre-defined
classes, interfaces and sub-packages. The built-in packages were included in JDK. These packages
contains a large number of classes and interfaces useful for different requirements. We can import
these packages in any Java program and can use the classes and interfaces of these packages in
that program.
There are many built-in packages in Java- java, util, io, lang, awt, swing etc.
java.awt : Contains classes for creating user interfaces and for painting graphics and images.
Classes like Button, Color, Event, Font, Graphics, Image etc are part of this package.
java.io : Provides classes for system input/output operations. Classes like BufferedReader,
BufferedWriter, File, InputStream, OutputStream, PrintStream, Serializable etc are part of this
package.
java.lang : Contains classes and interfaces that are fundamental to the design of Java
programming language. Classes like String, StringBuffer, System, Math, Integer etc are part of
this package.
java.sql : Provides the classes for accessing and processing data stored in a database. Classes
like Connection, DriverManager, PreparedStatement, ResultSet, Statement etc are part of this
package.
There is a need to import the built-in packages to use them in a program. To import a package we
use import statement.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Syntax:
import packagename.classname; //import single class
import packagename.*; //import whole package
If you use packagename.* then all the classes and interfaces of this package will be accessible
but not sub-packages.
If you import package.classname then only declared class of this package will be accessible.
User-defined Package:
The user-defined packages are the packages created by the user. User is free to create their own
packages.
To create a package – include a package command as the first statement in any Java source file.
Any class declared within that file will belong to the specified package. There can be only one
package statement in each source file.
If a package statement is not used then the classes, interfaces will be placed in the current default
package.
Syntax:
package pkgname;
pkgname – name of package
e.g.
package cs; //create a package cs
Access Modifier Within class Within package Outside package Outside package
subclass non-subclass
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
//Program in Java for the implementation of package
package cs;
public class Test
{
private int a=10;
int b=20;
protected int c=30;
public int d=40;
void disp()
{
System.out.println(“Inside main parent class:”);
System.out.println(“\na=”+a+”\nb=”+b+”\nc=”+c+”\nd=”+d);
}
}
//Main class
import cs.*;
import cs1.*;
class Exam
{
public static void main(String r[])
{
Test ob1=new Test();
Test1 ob2=new Test1();
Test2 ob3=new Test2();
Test3 ob4=new Test3();
Test4 ob5=new Test4();
ob1.disp();
ob2.disp1();
ob3.disp2();
ob4.disp3();
ob5.disp4();
}
}
Exception Handling:
An Exception is an unwanted or unexpected event that occurs during the execution of a program
(i.e., at runtime) and disrupts the normal flow of the program. It occurs when something
unexpected things happen, like accessing an invalid array index, dividing by zero, or trying to
open a file that does not exist. When an exception occurs, it is represented by an object of a subclass
of the java.lang.Exception class.
Exception handling is a mechanism to handle run-time errors so that normal flow program can be
maintained.
Exceptions can be caught and handled by the program. When an exception arises, an object
representing that exception is created and thrown in the method that caused the error. The object
is called exception object. It contains information about the exception such as name and description
of the exception.
Exception hierarchy:
All exceptions are subclasses of class Throwable, which is the base class of hierarchy.
One branch is headed by Exception- This class is used for exceptional conditions that the program
should catch. e.g. ArithmeticException
Another is headed by Error to indicate errors having that are not expected to be caught.
e.g. StackOverflow
Throwable
Exception Error
IOException StackOverflowError
SQLException
OutOfMemoryError
ClassNotFoundException
RuntimeException
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsEx
ception
1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that the
compiler verifies that the code handles these exceptions either by catching them or declaring them
in the method signature using the throws keyword.
IOException: An exception is thrown when an input/output operation fails, such as when reading
from or writing to a file.
ParseException: Indicates a problem while parsing a string into another data type, such as parsing
a date.
ClassNotFoundException: It is thrown when an application tries to load a class but the class
with the specified name cannot be found.
1. try block:
Program statements to monitor for exceptions are contained within a try block.
A try block cannot be executed on itself; it requires at least one catch block or finally
block.
If an exception occurs, the control flows from the try-to-catch block.
When an exception occurs in a try block, the appropriate exception object is redirected to
the catch block. This catch block handles the exception according to its statements and
continues the execution.
Syntax
try
{
// block of code monitor for exception.
}
2. catch block:
The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone.
The catch block handles the exception raised in the try block.
The catch block or blocks follow every try block.
The catch block catches the thrown exception and executes the statements inside it.
Syntax
try
{
// block of code monitor for exception.
}
catch(Exception e)
{
// code to handle exceptions
}
Output:
Divide by zero
After try/catch
//Another program for Java exception handling using try/catch
import java.util.*
class Test
{
public static void main(String r[])
{
int a,b,s;
Scanner ob=new Scanner(System.in);
try
{
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
s=a/b;
System.out.println(“s=”+s);
}
catch(ArithemeticException e)
{
System.out.println(“Divide by zero”);
}
System.out.println(“After try/catch”);
}
Displaying description of exception:
catch(ArithemeticException e)
{
System.out.println(“Exception:”+e);
}
Output:
Exception: java.lang.ArithmeticException:/ be zero
Output:
Exception:ArrayIndexOutOfBounsException
try
{
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
s=a/b;
System.out.println(“s=”+s);
System.out.println(“Value:”+c[3]);
}
catch(ArithemeticException e)
{
System.out.println(“Divide by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Exception :”+e);
}
catch(Exception e)
{
System.out.println(“Exception :”+e);
}
System.out.println(“After try/catch”);
}
*When we use multiple catch blocks, exception subclasses must come before any of their
superclass. This is because a catch statement that uses a superclass will catch exception of that
type plus any of its subclasses. Thus a subclass would never be reached if it come after its
superclass. In Java unreachable code is an error.
3. throw clause:
In Java it is possible to throw an exception explicitly, using throw statement. The throw keyword
is used to throw an exception explicitly. The flow of execution stops immediately after the throw
statement, any subsequent statements are not executed.
Syntax:
throw throwableinstance; //throwableinstance is an object of type Throwable or subclass
of Throwable
There are two ways to obtain a Throwable object: using a parameter in a catch block or creating
one with new operator.
e.g.
throw new ArithmeticException("/ by zero");
Instance must be of type Throwable or a subclass of Throwable.
4. throws clause:
It is used in the method signature to indicate that the method may throw mentioned exceptions. A
throws clause lists the types of exceptions that a method might throw. It is used only with checked
exceptions.
*If a method causing an exception but does handle that exception, then the method must specify
the behavior so that the caller of the method can guard themselves against that exception.
Syntax:
return-type method() throws eception1, exception2,---
{
//body of the method
}
class Exam
{
public static void main(String r[])
{
int a,b;
Scanner ob=new Scanner(System.in);
System.out.println(“Enter value for a and b”);
a=ob.nextInt();
b=ob.nextInt();
Test ob=new Test(a,b);
try
{
ob.calc();
}
catch(ArithemeticException e)
{
System.out.println(“Exception:”+e);
}
System.out.println(“After try/catch:”);
}
}
5. finally:
The finally block contains block of code that will execute regardless of whether the exception has
occurred or not. Java finally block is always executed even if there are no exceptions. It is an
optional block. The finally block executes after try..catch block. It is used to execute important
statements such as releasing resources, and releasing memory.
Syntax:
try {
// Code that may throw an exception
}
catch (ExceptionType e)
{
// Code to handle the exception
}
finally
{
// Code that will always execute
}
}
}
//Java program for the implementation of finally block
public class Test
{
public static void main(String[] args)
{
int a=5,b;
try
{
int b = 50 / a;
System.out.println("b=”+b);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: " + e);
}
finally
{
System.out.println("Finally block is always executed");
}
System.out.println(“After try/catch:”);
}
}