Why Java allows increasing the visibility of protected methods in child class?

Why decreasing visibility is not allowed is already explained in other responses (it would break the contract of the parent class).

But why it is allowed to increase the visibility of a method? First, it would not break any contract, so there is no reason to not allow it. It can be handy sometimes, when it makes sense in the child class for a method to not be protected.

Second, not allowing it could have the side effect of making impossible sometimes to extend a class and implement an interface at the same time:

interface Interface1 {
   public void method();
}

public class Parent {
   protected abstract void method();
}

public class Child extends Parent implements Interface1 {
   @Override
   public void method() {
   }
   //This would be impossible if the visibility of method() in class Parent could not be increased.
}

About your second question, you can do nothing about it. You have to trust that the person who implements the child class doesn’t do anything that breaks your implementation. Even if java wouldn’t allow to increase visibility, that would still not fix your problem, because a public method with a different name could be created that calls the abstract method:

class Child extends Base{
      @Override
      protected void a(){

      }

      public void a2() {
           a(); //This would have the same problems that allowing to increase the visibility.
      }
}

Leave a Comment