Multilevel Inheritance Example Java Program

Definition

Inheritance is when an object or class is based on another object or class, using the same implementation specifying implementation to maintain the same behaviour. It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a hierarchy. In multilevel inheritance a subclass is inherited from another subclass. It is not uncommon that a class is derived from another derived class as shown in the figure "Multilevel Inheritance". 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. The class B is known as intermediate base class since it provides a link for the inheritance between A and C.

Syntax

class A{
	//Do something
}
class B extends A{
	//Do something
}
class C extends B{
	//Do something
}

Multilevel Inheritance Example Program

class MultilevelInheritance{
	protected String str;
	MultilevelInheritance() {
		str = "This ";
	}
}
 
class ChildClass1 extends MultilevelInheritance {
	ChildClass1() {
		str = str.concat("is ");
	}
}
 
class ChildClass2 extends ChildClass1 {
	ChildClass2() {
		str = str.concat("Multilevel Inheritance ");
	}
}
 
class ChildClass3 extends ChildClass2 {
	ChildClass3() {
		str = str.concat("Example.");
	}
	void display() {
		System.out.println(str);
	}
}
 
class MultilevelInheritanceMain {
	public static void main(String args[]) {
		ChildClass3 obj = new ChildClass3();
		obj.display();
	}
}




Sample Output

Output is:
This is Multilevel Inheritance Example.