为什么不允许降低可见性是已经在其他响应中解释了(它会破坏父类的合同).
但为什么允许增加方法的可见性?首先,它不会违约,所以没有理由不允许.有时候,当一个方法没有被保护的小孩类中是有意义的,它可以很方便.
第二,不允许它可能会产生不可能的副作用,有时可以同时扩展一个类并实现一个接口:
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.
}
关于你的第二个问题,你什么也不做.你必须相信执行子类的人没有做任何打破你的实现的事情.即使Java不允许增加可见性,仍然无法解决您的问题,因为可以创建一个调用抽象方法的具有不同名称的公共方法:
class Child extends Base{
@Override
protected void a(){
}
public void a2() {
a(); //This would have the same problems that allowing to increase the visibility.
}
}