当您覆盖方法时,您不能降低继承方法的可见性。根据下表,protected
比 no modifier
更易于访问:
| Class | Package | Subclass | World ————————————+———————+—————————+——————————+——————— public | y | y | y | y ————————————+———————+—————————+——————————+——————— protected | y | y | y | n ————————————+———————+—————————+——————————+——————— no modifier | y | y | n | n ————————————+———————+—————————+——————————+——————— private | y | n | n | n y: accessible n: not accessible
But when I try to override f()
(see SubClass) then I get the error:
Cannot reduce the visibility of the inherited method from MyInterface.
The method in MyInterface has no access modifier and the one in SubClass is protected, so more accessible. What am I missing here?
public interface MyInterface {
void f();
}
public abstract class MyClass {
protected abstract void f();
}
public class SubClass extends MyClass implements MyInterface{
protected void f() { }
}
最佳答案
接口(interface)中的方法 implicitly具有 public
的访问修饰符。因此,当您使用 protected
实现它时,它是一个较弱的访问修饰符。
关于java - 使用 protected 访问修饰符覆盖没有访问修饰符的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32345165/