简体   繁体   English

从超类访问阴影变量

[英]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. 从这个anwser ,他说,我们可以通过铸造访问从超的超阴影变量this ,但因为方法调用是基于运行时类型的对象确定它不会对方法调用工作。

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? 如果我正确理解了他的答案,那么getT3getT2getT1getI方法都不应该全部返回3吗?

Because the method signatures expect I , T1 , T2 , and T3 , the parameters are treated as those types when returning ix , t1.x , etc. 因为方法签名期望IT1T2T3 ,所以在返回ixt1.x等时,参数将被视为那些类型。

So calling getT2(this) is essentially equivalent to calling getT2((T2) this) . 因此,调用getT2(this)本质上等同于调用getT2((T2) this)

That's why they would not all return 3, but rather the value of x for that specific type. 这就是为什么它们不会全部返回3,而是返回该特定类型的x的原因。

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 . 我不确定我是否已经对此进行了很好的解释,但是由于T3扩展了T2 ,因此在传递给getT2时,它隐式地转换为T2的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM