Write a Java program to Method Overriding with Covariant Return Types


This Java program illustrates the concept of method overriding and polymorphism when dealing with different return types. In this program, there are two classes: Animal (the parent class) and Dog (the child class), and the Dog class overrides the makeSound method of the Animal class. Here's an explanation of the program:

  • public class ReturnTypes: This is the main class that contains the main method, the entry point of the program.
  • public static void main(String[] args): The main method is where the program execution starts. It creates an object of the Dog class but assigns it to a reference variable of the Animal class, demonstrating polymorphism. Then, it calls the makeSound method on this object.
  • Animal animal = new Dog();: This line creates an object of the Dog class, but it's assigned to a reference variable of the Animal class. This is possible because a subclass object can be referred to by a reference variable of its superclass. This is an example of polymorphism and is used to demonstrate method overriding.
  • System.out.println(animal.makeSound());: This line calls the makeSound method on the animal object, and it prints the result to the console.
  • class Animal: This is the parent class, which has a method named makeSound that returns a string.
  • String makeSound(): The makeSound method in the Animal class returns the string "Animal Makes a Sound."
  • class Dog extends Animal: This is the child class that inherits from the Animal class.
  • @Override String makeSound(): The Dog class overrides the makeSound method of the Animal class. It returns the string "Dog Barks."

In this program, when the makeSound method is called on the animal object, which is a Dog instance but referenced as an Animal, the overridden version of the method in the Dog class is executed. This demonstrates polymorphism, where the actual method executed depends on the runtime type of the object rather than the reference type. As a result, "Dog Barks" is printed to the console.


Source Code

public class ReturnTypes  // Main class
{
	public static void main(String[] args)
	{
		Animal animal = new Dog();
		System.out.println(animal.makeSound());
	}
}
 
class Animal   // Parent class
{
	String makeSound()
	{
		return "Animal Makes a Sound";
	}
}
 
class Dog extends Animal  // Child class
{
	@Override
	String makeSound()
	{
		return "Dog Barks";
	}
}

Output

Dog Barks