7

OUTPUT:B

Why does virtual machine call this method f(null){System.out.println("B");}?

Why not f(null){System.out.println("A");}

public class Test{

    public static class A {}
    public static class B extends A {}

    public void f(A a) {System.out.println("A");}
    public void f(B a) {System.out.println("B");}

    public static void main(String[] args) {
        new Test().f(null);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

7

The method with most specific parameter type is called. Thats the rule This is from JLS section 15.12.2.5

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56