class AnimalClass{
void eat(){System.out.println("eating...");}
}
class Dog extends AnimalClass{
void bark(){System.out.println("barking...");}
}
class InheritanceClass{
public static void main(String args[]){
Dog obj=new Dog();
obj.bark();
obj.eat();
}
}
barking... eating... Press any key to continue . . .
This code demonstrates single inheritance in Java. The AnimalClass is a base class that has a method named eat(). The Dog class extends the AnimalClass and has an additional method called bark(). The InheritanceClass contains the main method and creates an object of Dog class to access its methods.
When the program runs, it creates an object of the Dog class and calls the bark() method, which prints "barking..." to the console. It then calls the eat() method, which is inherited from the AnimalClass and prints "eating..." to the console. This demonstrates how the Dog class inherits the behavior of the AnimalClass and extends it with its own behavior.
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.