Subclass Method Overrides Superclass Method In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method from its superclass

The code defines a simple hierarchy of classes in Java, and it demonstrates method overriding, which is a fundamental concept in object-oriented programming. Here's an explanation of the code:

  • Animal is the base class, and it has a method called makeSound. This method prints "Animal makes a sound" to the console.
  • Dog is a subclass of Animal. It overrides the makeSound method from the Animal class with its own implementation, which prints "Dog Barks" to the console.
  • In the Main class, you create an instance of the Dog class named dog.
  • You call the makeSound method on the dog object using dog.makeSound(). Since Dog is a subclass of Animal and it has overridden the makeSound method, it will call the makeSound method from the Dog class, and "Dog Barks" will be printed to the console.

Source Code

class Animal
{
    void makeSound()
	{
        System.out.println("Animal makes a sound");
    }
}
 
class Dog extends Animal
{
    @Override
    void makeSound()
	{
        System.out.println("Dog Barks");
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Dog dog = new Dog();
        dog.makeSound();
    }
}

Output

Dog Barkss