3
class Test {

   public Test(Object obj) {
      System.out.println("Object");
   }

    public Test(String s) {
       System.out.println("String");
   }

    public static void main(String[] args) {
       new Test(null); //prints String. Why not Object?
    }
}

If I add another constructor with argument of type Integer ,or, for that matter any other type, calling new Test(null); results in compilation error - The constructor Test(Object) is ambiguous.

Why no error is generated for the above example? On executing it, constructor with argument String is called. Why constructor with argument type Object is not called? How this ambiguity is resolved?

Nishant
  • 1,142
  • 1
  • 9
  • 27

3 Answers3

3

//prints String. Why not Object?

Because compiler choose most specific type.

If I add another constructor with argument of type Integer ,or, for that matter any other type, calling new Test(null); results in compilation error - The constructor Test(Object) is ambiguous.

Now String and Integer are in the same level in the object hierarchy, So, compiler can't choose one out of those two

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
2

Because it is determined by the most specific type of the parameter.

Since String is subclass of Object, and null is subtype of anything, then the second constructor is called, because String is more specific than Object.

WoDoSc
  • 2,598
  • 1
  • 13
  • 26
0

Compiler is designed to pick up the overloaded method that very closely matches the Value sent in parameter.

Vihar
  • 3,626
  • 2
  • 24
  • 47