Java Clear Concepts: Can we override protected method?


Protected method can be overridden by subclass. What are permitted access specifiers of sub class overridden method when super class method is protected? Discussed clearly with Example and Screenshot for a Beginner.

The answer for the question is "YES". "protected" methods of super class can be overridden by subclass (but private methods cannot be overridden).

Following example on Protected method proves.
class Test
{
  protected void display() 
  {  
    System.out.println("\nFrom Test");
  }
}
public class Demo extends Test
{
  protected void display() 
  {
    super.display();				    // prints "From Test"  
    System.out.println("From Demo");		    // prints "From Demo"  
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();
    d1.display();
  }
}

Screenshot on Protected method of the above example.

Protected method

Observe, in the super class Test, display() is protected and is overridden by subclass Demo and also calling super class display() with super keyword.

What are the permitted access specifiers of sub class overridden method when the super class method is protected? What are the restrictions?

If the super class method is protected, the subclass overridden method can have protected or public (but not default or private). The rule says, the sub class overridden method should not have a weaker access specifier. It is explained more cearly in Rules of Access Specifiers in Method Overriding and Why the methods of an interface should be overridden as public only?.

Leave a Comment

Your email address will not be published. Required fields are marked *