Inheritance
Introduction
• One of the most effective features of OOP’s
paradigm.
• Establish a link/connectivity between 2 or
more classes absorbs the members of an
existing class, and enhancing them by adding
new members or modifying the functionality
of the inherited class.
• Permits sharing and accessing properties from
one to another class
• To establish this relation Java uses ‘extends’
keyword.
Category of Classes on the Basis of
Inheritance
• Super class (base/parent/driver/inheritance/
ancestor class).
• Intermediate class (mediating/dual class).
• Sub class (Child/associate/derived/inherited
class).
The syntax of Java Inheritance
• The keyword used is “extends”
class Subclass-name extends Superclass-name
{
//methods and fields
}
Note: The meaning of "extends" is to increase the functionality.
Types of inheritance in java
• On the basis of class, there can be three types
of inheritance in java:
– single,
– multilevel and,
– hierarchical.
• In java programming, multiple and hybrid
inheritance (that contain multiple inheritance)
is supported only through interface.
Single Inheritance
Single Inheritance: refers to a child and parent
class relationship where a class extends the
another class.
class A{
int x;
int y; class inheritancetest{
public void initialize(){ public static void main(String args[]){
x=5; B b = new B();
y=7; [Link]();
} [Link]();
public void add(){ b.p=9;
int z=x+y; b.q=5;
[Link](z); [Link]();
} }
} }
class B extends A{
int p,q;
public void sub(){
int a=p-q;
[Link](a);
}
}
class A{
int x;
int y;
A(){
x=5;
y=7; class inheritancetest1{
}
A(int x,int y){
public static void main(String
this.x=x; args[]){
this.y=y; B b = new B();
}
public void add(){ [Link]();
int z=x+y; [Link]();
[Link](z);
}
B b1 = new B(4,5,6,7);
} [Link]();
class B extends A{
int p,q;
[Link]();
B(){ }
p=9; }
q=4;
}
B(int x,int y,int p, int q){
super(x,y);
this.p=p;
this.q=q; But if you want to call a
}
public void sub(){ parameterized constructor of the
int a=p-q; superclass, you need to use the
[Link](a); super keyword
}
}
Multilevel inheritance
• Multilevel inheritance: refers to a child and
parent class relationship where a class extends
the child class.
Hierarchical inheritance
• Hierarchical inheritance: refers to a child and parent
class relationship where more than one classes
extends the same class. For example, classes B, C & D
extends the same class A.
Output::
method of Class A
method of Class A
method of Class A