Sunday, April 9, 2017

Overriding - Access Level

When method is overriding in subclass the access modifier should be taken into consideration otherwise there will be compilation error. The rule is that access level of overriding methods should not be restrictive than the overridden method in parent class.

In this example we have method eat() with public access modifier but subclass overriding version defined with protected which is restrictive than public. Method sleep() with protected access modifier but subclass overriding version defined with private which is also restrictive than protected. So it violates to the overriding rule.

class X
{
  public void eat() {}
  protected void sleep() {}
}

class Y extends X
{
  protected void eat() {}
  private void sleep() {}
}

public class OverridingAccessTest
{
  public static void main(String args[])
  {
  
  }
}

Results:
OverridingAccessTest.java:9: error: eat() in Y cannot override eat() in X
  protected void eat() {}
                 ^
  attempting to assign weaker access privileges; was public

OverridingAccessTest.java:10: error: sleep() in Y cannot override sleep() in X
  private void sleep() {}
               ^
  attempting to assign weaker access privileges; was protected
2 errors

No comments:

Post a Comment

Abstraction vs Interface

Abstract Interface method abstract and concrete abstract only, support default and static method ...