Way2Java

Rules of Access Specifiers in Method Overriding

Access Specifiers Method Overriding: The only rule says:

"The subclass overridden method cannot have weaker access than super class method".

Let us see the above rule practically in Access Specifiers Method Overriding.
class Test
{
  protected void display()         // protected specifier
  {
    System.out.println("Hello 1");
  }
}
public class Demo extends Test
{
  void display()                   // overridden with default specifier
  {
    System.out.println("Hello 2");
  }
  public static void main(String args[])
  {    
    new Demo().display();
  }
}



Output screen of Access Specifiers Method Overriding

Protected display() method of Test class is overridden by Demo class with default (not specified at all) access. It raises compilation error. The subclass can have either same or stronger access like public or same protected. But, it cannot have default or private.

Why the methods of an interface should be overridden with public only?

With the above rule, now you get the answer. The methods of an interface must be public, if not mentioned, takes by default as public. So, the subclass which implements the interface should override with the same specifier or more but not less. No stronger specifier than public exists in Java. For this, reason, all the methods of interface must be overridden with public only.

Rules of exceptions also must be taken care in method overriding.