Write a Java program to demonstrates accessing superclass members using the super keyword


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:

  • class Dog extends Animal: This is the Dog class, which inherits from the Animal class. It contains a method called displaySound.
  • @Override void displaySound(): The displaySound method in the Dog class is marked with the @Override annotation, indicating that it overrides the same method in the parent class. In this method, it calls the displaySound method of the parent class using super.displaySound(), which is then followed by the specific behavior for the Dog class (printing "Dog barks" to the console).
  • public static void main(String[] args): This is the main method, the entry point of the program.
  • Dog dog = new Dog();: It creates an instance of the Dog class.
  • dog.displaySound();: This line calls the displaySound method on the dog object, which demonstrates method overriding.
  • class Animal: This is the parent class, which contains a method named displaySound.
  • void displaySound(): The displaySound method in the Animal class prints "Animal makes a sound" to the console.

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.


Source Code

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");
	}
}

Output

Animal makes a sound
Dog barks