MiP
MiP

Reputation: 6432

Access shadowed variables from superclasses

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?

Upvotes: 1

Views: 55

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

Because the method signatures expect I, T1, T2, and T3, the parameters are treated as those types when returning i.x, t1.x, etc.

So calling getT2(this) is essentially equivalent to calling getT2((T2) this).

That's why they would not all return 3, but rather the value of x for that specific type.

I'm not sure I've explained this well, but because T3 extends T2, it is implicitly cast to an instance of T2 when passed to getT2.

Upvotes: 2

Related Questions