Subclass Method Overrides Superclass Method with Private Access Modifier In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method and changes the access modifier to private

The Superclass with a protected method display, and a Subclass that attempts to override the display method but changes the access modifier to private. This is not allowed in Java because method overriding in a subclass should not reduce the visibility of the method compared to the superclass. Here's an explanation of the code:

  • Superclass is a class with a protected method display that prints a message to the console.
  • Subclass is a subclass of Superclass and tries to override the display method with a private access modifier. This is not allowed in Java because access modifiers should be the same or less restrictive in the subclass when overriding a method from the superclass. Changing from protected to private is more restrictive and not allowed.
  • In the MethodOverridingDemo class's main method, you create instances of both Superclass and Subclass.
  • You try to call the display method on both superObj and subObj.

Since you changed the access modifier to private in the Subclass, it will not compile. You will encounter a compilation error when you attempt to call subObj.display() due to the change in access modifier.

Source Code

class Superclass
{
    protected void display()
	{
        System.out.println("This is a protected method in the superclass.");
    }
}
 
class Subclass extends Superclass
{
    // This method attempts to change the access modifier to private
    // This will result in a compilation error
    private void display()
	{
        System.out.println("This is a private method in the subclass.");
    }
}
 
public class MethodOverridingDemo
{
    public static void main(String[] args)
	{
        Superclass superObj = new Superclass();
        Subclass subObj = new Subclass();
 
        superObj.display();
        subObj.display(); // This would not compile due to the access modifier change
    }
}
 

Output

attempting to assign weaker access privileges; was protected