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.nameis 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).
加载中,请稍侯......
精彩评论