This tutorial discusses Simple and Multilevel Inheritance in Java with examples. Use of super keyword in Multilevel Inheritance is also explained with an example.
In this tutorial we will discuss examples of Simple Inheritance in Java and Multilevel Inheritance in Java. Inheritance is an OOPS (Object Oriented Programming) concept, which allows a subclass to extend a parent class, inheriting some of its features.
extend and implement keywords are used for inheritance in Java.
The concept of inheritance is used to make the things from general to more specific.
Inheritance is used in java for the reusability of code of a parent class by a derived class. The derived class is called a subclass.
Java supports three types of inheritance:
- Simple inheritance
- Multilevel inheritance
- Hierarchical inheritance
Simple Inheritance
Here a parent class is extended by one sub class, It is also known as one level inheritance.
Example of Single Inheritance in Java:
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Multilevel Inheritance
Java does not support Multiple Inheritance DIRECTLY. But it can be achieved by using more than one interface in a class.
Here a parent class is extended by sub class. This sub class then acts as a parent class and is further extended by a sub class. Multilevel inheritance can go up to any number of levels.
*subclass cannot access members declared private in parent class
*subclass can extend only one parent class
Example of Multilevel Inheritance:
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}
super keyword is used to access the members of the parent class in multi-level inheritance.
super keyword not only access the hidden data variables of the parent class hidden by the sub class but is also used to call super class constructor in the subclass.
Following example explains the use of super keyword in Multi-level Inheritance:
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){
B subobj = new B(1, 5);
subobj.Show();
}
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Hierarchical inheritance:
Here parent class is extended by more than one sub class in a tree structure.