1

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()); 
    } 
}
Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45
SubZr0
  • 137
  • 7
  • I'm not sure that it's really a duplicate of that, as it's not asking how to select based on execution-time type. The answer is still relevant though... – Jon Skeet Aug 23 '16 at 12:22

1 Answers1

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194