简体   繁体   中英

Compile time Polymorphism and resolution of `this` keyword

I'm calling an overloaded method of some class ( c.doSomething ), from a class, and I'm passing the class instance as the argument.It is better explained using the following scenario:

public class A {

    protected int do(){
        C.doSomething(this);
    }
}

public class B extends A {

    public int doSomething(){
        do();
    }
}

public class C{
    public static function doSomething(B b){ System.out.println("b"); }
    public static function doSomething(A a){ System.out.println("a"); }

}

Now if I do something like the below in main , which of the doSomething methods will be called from C ?

B b = new B();
b.doSomething();

This is rightfully called "compile time polymorphism" since C.doSomething(A a) is called and we are calling C.doSomething inside A . It is interesting to note that putting a getClass() inside A.do will yield "B" when b.doSomething is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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