0

The below code has compilation issue,can some one explain ?How null is treated in this case? All Wrapper class giving the same issue.

public class MyTest {  
public static void main(String[] args) {    
    new MyTest().hello(null);
}

public void hello(Object o){
    System.out.println("object");
}

public void hello(Boolean o){
    System.out.println("Boolean");
}

public void hello(Double o){
    System.out.println("Double");
}
}

All Wrapper class giving the same issue:

The method hello(Object) is ambiguous for the type MyTest class.

assylias
  • 321,522
  • 82
  • 660
  • 783
Dhruva
  • 185
  • 1
  • 3
  • 15
  • 1
    Compiler cannot decide `null` denotes `Boolean` or `Double`. – johnchen902 Jun 28 '13 at 10:44
  • You should cast that `null` :D – Maroun Jun 28 '13 at 10:47
  • 1
    try to add 'public void hello(String o)' or `public void hello(MyObject o){`. they would be considered as ambiguous methods when you try to invoke the method by passing null – PermGenError Jun 28 '13 at 10:47
  • @PermGenError : yes,u r right.Can u explain this one public void hello(String o){ System.out.println("String"); } public void hello(Object o){ System.out.println("Object"); } In this case it will take the null as String.If the first case is not working then how the String case is working? – Dhruva Jun 28 '13 at 11:52

1 Answers1

0

null isn't really a type on its own so it does now know which overload to pick from.

You could try (Object) null and see what happens.

Further to this, null is an applicable value for Object and Double, it might be able to figure it out and compile if you only had a boolean and object (since it wouldn't choose boolean).

ddoor
  • 5,819
  • 9
  • 34
  • 41
  • In this case it will take the String method,without casting.So why this happen ?public void hello(String o){ System.out.println("String"); } public void hello(Object o){ System.out.println("Object"); } – Dhruva Jun 28 '13 at 11:46
  • This help a lot http://stackoverflow.com/questions/5229809/method-overloading-for-null-parameter – Dhruva Jun 28 '13 at 12:05
  • Because String extends object, so it calls the extension before the object... it compiles because they are both acceptable nulls – ddoor Jun 28 '13 at 12:05