Here is the code:
public class OverloadingByObject {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object object = null;
new OverloadingByObject().SayHi(null);
new OverloadingByObject().SayHi(object);
}
public void SayHi(String str) {
System.out.println("String called");
}
public void SayHi(Object obj) {
System.out.println("Object called");
}
}
When I am passing null it should call the method of Object. What is the reason it is calling method of String ?
null
can be assigned to any reference type. When deciding which overloaded version of a method will be called, the method with the most specific arguments is chosen. String
is more specific than Object
(since String
is a sub-class of Object
). Therefore SayHi(String str)
is called for a null
argument.