From this anwser, he said that we can access shadowed variables from superclasses of superclasses by casting this
, but it doesn't work for method calls because method calls are determined based on the runtime type of the object.
However, why can I still get shadowed variables without explicitly casting the passing parameter types?
interface I { int x = 0; }
class T1 implements I { int x = 1; }
class T2 extends T1 implements I { int x = 2; }
class T3 extends T2 implements I {
int x = 3;
void test() {
System.out.println("((T3)this).x=" + ((T3)this).x + "; getT3(this)=" + getT3(this));
System.out.println("((T2)this).x=" + ((T2)this).x + "; getT2(this)=" + getT2(this));
System.out.println("((T1)this).x=" + ((T1)this).x + "; getT2(this)=" + getT1(this));
System.out.println("((I)this).x=" + ((I)this).x + "; getI(this)=" + getI(this));
}
public static void main(String[] args) {
new T3().test();
}
int getT3(T3 t3) { return t3.x; }
int getT2(T2 t2) { return t2.x; }
int getT1(T1 t1) { return t1.x; }
int getI(I i) { return i.x; }
}
which produces the output:
((T3) this).x = 3; getT3(this) = 3
((T2) this).x = 2; getT2(this) = 2
((T1) this).x = 1; getT1(this) = 1
((I) this).x = 0; getI(this) = 0
If I understand his anwser correctly, shouldn't getT3
, getT2
, getT1
and getI
methods all return 3?