Hierarchical inheritance in java language
In this tutorial, we will discuss the subject of Hierarchical inheritance in java language
Hierarchical inheritance is when multiple classes inherit from a single class. There are one parent (super) class and many children(sub) classes. Hierarchical inheritance is supported in Java. In the example below, class B, class C and class D inherit the properties of class A. Class A acts as the parent class of class B, class C and class D.
In the diagram above, a class can have more than one child class (subclasses) or two or more children classes can only have one (same) parent class. Here, Class A acts as the parent for subclasses class B, class C and class D. This is known as hierarchical inheritance.
Let’s try to understand using the following syntax
Syntax
class A
{
public void method_A
{
//Block of code
}
}
class_B extends class_A
{
public void method_A
{
//Block of code
}
}
class_C extends class_A
{
public void method_A
{
//Block of code
}
}
class MainClass{
public static void main(String args[]){
B obj1=new B(); // object created class B
obj1.method_A(); //call method_A() method of class B
obj1.method_B(); //call method_B() method of class B
C obj2=new C(); // object created class C
obj2.method_C(); //call method_C() method of class C
obj1.method_A(); //call method_A() method of class C
}
}
Example
Program 1
Program 2
Related Links