JLS 8 关于关键字 super 和受保护的成员
JLS 8 regarding keyword super and protected members
在 JLS 8 15.11.2-1(第 505 页)中,我无法理解他们的意思:
Note that super.x
is not specified in terms of a cast, due to difficulties around access to protected
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
.
在 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
.