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:
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.
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 } }
attempting to assign weaker access privileges; was protected
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions