当你重写方法时,不允许减少继承方法的可见性。根据下表,
protected
比no modifier
更可访问:
| 类 | 包 | 子类 | 外部 ————————————+———————+—————————+——————————+——————— public | y | y | y | y ————————————+———————+—————————+——————————+——————— protected | y | y | y | n ————————————+———————+—————————+——————————+——————— no modifier | y | y | n | n ————————————+———————+—————————+——————————+——————— private | y | n | n | n但是当我尝试覆盖
y: 可访问 n: 不可访问
f()
(请参见SubClass)时,我会收到以下错误信息:
Cannot reduce the visibility of the inherited method from MyInterface.
MyInterface中的方法没有访问修饰符,而SubClass中的方法具有受保护的修饰符,因此更容易访问。 我在这里错过了什么?public interface MyInterface {
void f();
}
public abstract class MyClass {
protected abstract void f();
}
public class SubClass extends MyClass implements MyInterface{
protected void f() { }
}