0

Can someone explain me why if a run this code

public class MainClass{

   public void method(Object obj){
       System.out.println("+++++++++obj");
   }

   public void method(A a){
       System.out.println("**********a");
   }

   public static void main(String[] args){
       new MainClass().method(null);
   }
}

I get this result:

**********a

How can a null reference be resolved to an "A" object reference?

laks.it
  • 165
  • 14
  • 4
    `null` can be resolved to anything and thus the most specific method will be used. Add a method with parameter type `B` and the compiler should complain about ambiguous parameters. – Thomas Sep 25 '15 at 09:19
  • This isn't overriding, it's overloading - and it doesn't seem *terribly* obscure to me. Would you expect `A a = null;` to fail to compile? – Jon Skeet Sep 25 '15 at 09:23

1 Answers1

6

Most specific method chooses at run. A is more specific than Object and

A a = null;

is valid.

Hence when you pass null, its choosing (A a).

Here is the Language specification

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307