Let us take both the cases one by one:
Case 1: When we have two disp overloaded
function, one with parameter Object
and other with parameter String
:
public void disp(String s) { System.out.println("String called :"+s); }
public void disp(Object o) { System.out.println("Object called :"); }
In this case, it will refer to the most specific method. According to Java Docs JLS 15.12.2.5:
A method m1 is strictly more specific than another method m2 if and
only if m1 is more specific than m2 and m2 is not more specific than
m1.
So, in above case, the function accepting String
is more specific then the one accepting Object
, however, the opposite is not true.
Hence, in this case, when null
is passed, it will go to the method with parameter String. But if you will pass (Object)null
, it will go to the method with parameter Object.
car.disp(null); --> String called :null
car.disp((Object)null); --> Object called :
Case 2: When we have two disp overloaded
function, one with parameter String
and one with parameter Integer
.
public void disp(String s) { System.out.println("String called :"+s); }
public void disp(Integer i) { System.out.println("Integer called :"+ i); }
In this case, as none of the method is more specific then the other and both the function can accept null value, an appropriate function can not be decided in case of null
. However, if you will pass (Integer)null
or (String)null
, no ambiguity will be there and appropriate function can be called.
car.disp(null); --> Compile time error (The method disp(String) is ambiguous for the type Car)
car.disp((Integer)null); --> Integer called :null
car.disp((String)null); --> String called :null