質問

     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