Subclass Method Broadens Access Modifier from Protected to Public In Java


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

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 an explanation of the code:

  • 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.

However, in your Dog class, you changed the access modifier of the makeSound method to public. This is allowed in Java, but it's important to note that it makes the method in the subclass more accessible than the method in the superclass.

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 with the public access modifier, 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
    public 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