在 JLS 8 15.11.2-1 (第505页),我不明白他们的意思:
Note that
super.x
is not specified in terms of a cast, due to difficulties around access toprotected
members of the superclass.
有什么帮助吗?
最佳答案
考虑一下:
public class T2 {
protected int x = 2;
}
/* in a different package */
public class T3 extends T2 {
int x = 3;
void test() {
System.out.println(this.x); // prints 3
System.out.println(super.x); // prints 2
T2 this_as_t2 = (T2)this;
System.out.println(this_as_t2.x); // Error: Can't access protected member x of class T2
System.out.println(((T2)this).x); // Same error as above
}
}
如果 super.x
等同于 ((T2)this).x
,那么您将无法使用 super.x
引用 T2
中的 x
字段。
所以规范没有说它们是等价的(因为它们并不总是相同)。但是,在某些情况下它们仍然是等效的 - 例如,如果两个类位于同一个包中,或者字段是 public
。
关于java - JLS 8 关于关键字 super 和 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596601/