Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast to to super not working as expected

Tags:

java

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();
    }
}
like image 507
Saideira Avatar asked Dec 27 '22 13:12

Saideira


1 Answers

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();
    }
like image 51
NPE Avatar answered Jan 05 '23 04:01

NPE