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();
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With