0

I am using below code to check which overloaded method will be called. Why do I see String : null in the output instead of ambiguity or Object : null?

public class Employee {

    public void display(Object o){
        System.out.println("Object : "+ o);
    }
    public void display(String s){
        System.out.println("String : " + s);
    }


    public static void main(String[] args) {
        Employee employee = new Employee();
        employee.display(null);
    }

}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 2
    The Java selection rules for overloaded methods choose the most specific type for null. And the most specific type here is `String`, not `Object`. – Mark Rotteveel Feb 24 '22 at 10:07
  • 1
    **tl;dr** for the dupe: because the rules say to use the "most specific" version of the method that's applicable. And `String` is more specific than `Object`. – Joachim Sauer Feb 24 '22 at 10:07
  • From [JLS](https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.12.2.5): "The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error." Any String can be passed to either the String or Object overload, but some Objects cannot be passed to the String overload: thus, `display(String)` is more specific. – Andy Turner Feb 24 '22 at 10:10
  • If you changed `display(Object o)` to `display(Integer i)`, then the compiler would emit an error, because between `Integer` and `String`, there no most specific type, as neither is a subclass of the other. – MC Emperor Feb 24 '22 at 10:10
  • Thank you for the answers. Really appreciate the help. – Rahul Kumar Feb 24 '22 at 19:41

0 Answers0