Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why constructor call is not ambiguous in the following example? [duplicate]

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?

like image 542
Nishant Avatar asked Dec 17 '25 15:12

Nishant


1 Answers

//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

like image 69
Abimaran Kugathasan Avatar answered Dec 19 '25 03:12

Abimaran Kugathasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!