-1
public class CompilerConfuse {

    public static void main(String[] args) {

        A a =new A();
        a.method(null); // error line

    }

}


class A
{

     public void  method(Integer a)
     {
         System.out.println("In Integer argument method" + a);
     }

     public void  method(Object a)
     {
         System.out.println("In Object argument method" + a);
     }

     public void  method(String a)
     {
         System.out.println("In String argument method " + a);
     }
}

In Integer and String overload method,Compiler could not able to decide which one to call.Why this happening?

If we remove either of String or Integer overload method it is not giving error when passing null.

Emanuele Giona
  • 781
  • 1
  • 8
  • 20

1 Answers1

-1

The compiler selects the method the most specific according to the type of the passed argument(s).
In your case, String and Integer are more specific than Object but both are also as much specific, so the compiler doesn't chose between and emits a compilation error.

You can refer to 15.12.2.5. Choosing the Most Specific Method :

It is possible that no method is the most specific, because there are two or more methods that are maximally specific. In this case:

If all the maximally specific methods have override-equivalent signatures (§8.4.2), then:

...

Otherwise, the method invocation is ambiguous, and a compile-time error occurs.

Community
  • 1
  • 1
davidxxx
  • 125,838
  • 23
  • 214
  • 215