How is this call to method resolved in Inheritance in java?

Why doAction(A a) will be selected in this situation?

Can you advice some articles to read about method selection depending on argument type?

class A { } 
class B extends A { } 
class D {
    void start(A a){ 
        doAction(a); 
    }
    void doAction(A a) { 
        System.out.println("A action"); 
    } 
    void doAction(B b) { 
        System.out.println("B action"); 
    } 
} 
public class Test { 
    public static void main(String[] args) { 
        new D().start(new B()); 
    } 
}
Jon Skeet
people
quotationmark

Why doAction(A) will be selected in this situation?

Because it's the only applicable method. Overload resolution is performed at compile-time, based on the compile-time type of the arguments.

The doAction(B) method isn't applicable, because there's no implicit conversion from A (the type of your argument) to B (the type of the parameter). You could cast the value to B like this:

doAction((B) a);

At that point both methods would be applicable, but overload resolution would pick doAction(B b) as being more specific than doAction(A a). Of course, it will also fail if you pass in a reference which isn't to an instance of B.

You should read JLS 15.12.2 for the precise details of overload resolution.

people

See more on this question at Stackoverflow