문제

     public class Test {

   public void method(String param)
   {
       System.out.println("String version");
   }

   public void method(StringBuffer param)
   {
       System.out.println("String Buffer");
   }

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

This code result is compilation error says “reference to method is ambiguous”

    public class Test
{
    public void method1(Object param)
    {
        System.out.println("Object Version ");
    }

    public void method1(String param)
    {
        System.out.println("String Version ");
    }

    public static void main(String[] args)
    {
        Test test=new Test();
        test.method1(null);
    }
}

This code result is “String Version”

Actually I can’t understand the result of second piece of code. Why don’t both piece of code has the same result

도움이 되었습니까?

해결책

In first case,

null is a subtype of every other reference type. So, compiler finds ambiguity in deciding which method to call..

In second case, it finds more specific object for null which happens to be String. Hence it calls method1 and prints String Version

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top