0

Please explain why i'm getting "Method with String param" in output. And when i remove the comments from display(Test x) method, it says "Reference to display is ambiguous".

class Test 
{    
    int a;
    int b;
}

public class TestIt 
{    
    public static void display(String x)
    {
       System.out.println("Method with String param");
    }

    public static void display(Object x)
    {
       System.out.println("Method with Object param");
    }
/*    
    public static void display(Test x)
    {
        System.out.println("Method with Test param");
    }
*/    
    public static void main(String args[])
    {
        display(null);        
    } 

}
Dams
  • 47
  • 7

2 Answers2

1

Because null is a valid value for Object and String. You can cast,

display((String) null);  

Will output

Method with String param

or

display((Object) null);  

for

Method with Object param
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Because when figuring out which method to call, the compiler picks the most specific method it can find that matches the argument. Both display(String) and display(Object) match a call to display(null), but display(String) is more specific than display(Object), so the compiler uses that. When you uncomment the display(Test) version, though, the compiler can't make a choice because both display(String) and display(Test) are equally specific.

For all the gory details, see §15.12 of the JLS.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875