In JLS 8 15.11.2-1 (page 505), I cannot understand what they mean by:
Note that
super.x
is not specified in terms of a cast, due to difficulties around access toprotected
members of the superclass.
Any help?
Consider this:
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
}
}
If super.x
was equivalent to ((T2)this).x
, then you wouldn't be able to use super.x
to refer to the x
field in T2
.
So the specification does not say they're equivalent (because they aren't always). However, they're still equivalent in some situations - such as if both classes are in the same package, or if the field is public
.