java重写和弱化访问修饰符
An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:
C is a subclass of A.
The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
Either:
m2 is public, protected, or declared with default access in the same package as C, or
m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.
这似乎与以下代码并不矛盾:
public class Main {
public void f() { }
public static class A extends Main {
protected void f() { }
}
public static void main(String[] args) {
}
}
但是它不是编译,即使方法f()
的重写版本有protected
访问修饰符,正如我在提供的规则的第二点中所说的。怎么了
# 1 楼答案
不能使用更严格的访问修饰符重写方法。方法f()是用访问修饰符
public
声明的,但您正试图用protected
修饰符覆盖它,后者限制性更强。改变到
# 2 楼答案
这方面的理由在以下JLS中提供8.4.8.3:
请注意,您在问题中引用的部分基本上说明了“基类中方法的访问修饰符不能是私有的”,并且与重写方法的访问修饰符完全无关