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();
}
}
weeping... barking... eating... Press any key to continue . . .
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.
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.