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 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.