This Java program illustrates the concept of method overriding and how a subclass can call a method from its superclass using the super keyword. In this program, there are two classes: Animal (the parent class) and Dog (the child class). The Dog class extends the Animal class and overrides the displaySound method. Here's an explanation of the program:
In this program, when the displaySound method is called on the dog object, it executes the overridden version of the method in the Dog class. However, using super.displaySound() allows it to call the parent class's version of the method, printing "Animal makes a sound" first, and then the specific behavior for the Dog class, which is "Dog barks." This demonstrates method overriding and how the super keyword can be used to access a superclass method in the context of a subclass.
class Dog extends Animal { @Override void displaySound() { super.displaySound(); // Access superclass method System.out.println("Dog barks"); } public static void main(String[] args) { Dog dog = new Dog(); dog.displaySound(); } } class Animal { void displaySound() { System.out.println("Animal makes a sound"); } }
Animal makes a sound Dog barks
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions