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 understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.