Subclass Method Changes Access Modifier from Public to Private In Java


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

The code defines override a method in a subclass while changing the access modifier from public in the superclass to private in the subclass. This code illustrates a fundamental concept in object-oriented programming, specifically in Java, known as method overriding and access control. Here's an explanation of the code step by step:

  • Superclass is a class that defines a public method called display. This method prints "This is a public method in the superclass." to the console.
  • Subclass is another class that extends Superclass. In the Subclass, there's an attempt to override the display method from the Superclass. However, in the Subclass, the display method has its access modifier changed to private, which is more restrictive than the public access modifier in the Superclass. This is not allowed in Java and will result in a compilation error.
  • In the MethodOverridingDemo class, the main method is defined, and you create instances of both Superclass and Subclass.
  • You then attempt to call the display method on both superObj and subObj. However, the code would not compile due to the access modifier change in the Subclass.

The key points to understand are:

  • In method overriding, a subclass provides its own implementation of a method defined in its superclass.
  • When overriding a method in a subclass, the access modifier of the overridden method in the subclass must be the same as or more permissive than the access modifier of the method in the superclass. This is an essential rule in Java. In your code, changing the access modifier from public to private in the Subclass violates this rule, leading to a compilation error.

Source Code

class Superclass
{
    public void display()
	{
        System.out.println("This is a public 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 public