开发者

cast to to super not working as expected

Why does the second call produces what it does? I thought that by casting this to Super, only Super's m1() should be called!!

Super!
And Sub!
---
Super!
And Sub!

Code:

public class TestSuper {
    public static void main(String[] args) {
        (new Sub()).m1();
        System.out.println("---");
        (new Sub()).m2();                // !!!!!!!!!!!!!!!!
    }
}

class Super {
    void m1() {
        System.out.println("Super!");
    }
}

class Sub extends Super {
    void m1() {
        super.m1();
        System.out.println("And Sub!");
    }

    void m2() {
        ((Super) this).m1(开发者_StackOverflow社区);
    }
}


No, casting won't help since it's the dynamic type of the object that's used to select the m1 to call.

The following does the trick:

    void m2() {
        super.m1();
    }


This is a good question. According to JLS §15.11.2,

super.name is treated exactly as if it had been the expression ((S)this).name

But this only applies to fields of a class, not methods (as noted by @ILMTitan).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜