Home / Programs / Multilevel Inheritance in java
Programming Example

Multilevel Inheritance in java

👁 3,479 Views
💻 Practical Program
📘 Step by Step Learning
Multilevel inheritance in Java is a type of inheritance where a derived class inherits properties and behaviors from a parent class, which in turn inherits from its own parent class. In this type of inheritance, a subclass becomes a parent class for another class. This article explains how multilevel inheritance works in Java and provides examples.

Program Code

 class Animal{
void eat(){
	System.out.println("eating...");
	}
}

class Dog extends Animal{
 void bark(){System.out.println("barking...");
 }
}

class BabyDog extends Dog{
 void weep(){System.out.println("weeping...");
 }
}

class MultilevelInheritance{
	public static void main(String args[]){
	BabyDog d=new BabyDog();
	d.weep();
	d.bark();
	d.eat();
	}
}

  

Output

weeping...
barking...
eating...
Press any key to continue . . .

Explanation

This Java code demonstrates multilevel inheritance where the BabyDog class extends the Dog class, which in turn extends the Animal class. The Animal class has a method called eat() that prints "eating...". The Dog class has a method called bark() that prints "barking...". The BabyDog class has a method called weep() that prints "weeping...". In the main() method of the MultilevelInheritance class, an instance of the BabyDog class is created and its methods are called. This code shows how a subclass can inherit properties and behaviors from multiple levels of superclasses.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.