没有带受保护访问修饰符的访问修饰符的java重写方法
重写方法时,不允许降低继承方法的可见性。根据下表,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
但是当我试图重写f()
(请参见子类)时,我得到了错误:
无法降低从MyInterface继承的方法的可见性
MyInterface中的方法没有访问修饰符,子类中的方法受到保护,因此更容易访问。我错过了什么
public interface MyInterface {
void f();
}
public abstract class MyClass {
protected abstract void f();
}
public class SubClass extends MyClass implements MyInterface{
protected void f() { }
}
# 1 楼答案
在java接口中, 所有的方法都是公开的。 所有变量都是公共静态最终变量。(常数)
# 2 楼答案
接口方法与生俱来的public
给予
或者
在MyInterface中,查看您得到了什么
# 3 楼答案
接口中的方法被隐式标记为
public
,而不是default
# 4 楼答案
接口implicitly中的方法具有
public
的访问修饰符。因此,当您使用protected
实现它时,它是一个较弱的访问修饰符# 5 楼答案
来自Javadoc:
接口中的方法默认为
public
。因此,不能使用public
以外的任何修饰符重写/隐藏此方法