Subclass Method Narrows Access Modifier from Public to Protected In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method and narrows the access modifier from public to protected

Class hierarchy with a base class Animal and a subclass Dog. The makeSound method is declared in the Animal class and overridden in the Dog class. Here's a breakdown of what your code does:

  • Animal is a class with a protected method makeSound that prints "Animal makes a sound" to the console.
  • Dog is a subclass of Animal. It overrides the makeSound method with its own implementation, printing "Dog barks" to the console.
  • In the Main class, you create an instance of the Dog class and call the makeSound method on the dog object.

When you run the code, it will create a Dog object and call the makeSound method. Since the makeSound method is overridden in the Dog class, it will print "Dog barks" to the console.

Source Code

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

Output

Dog barks