When overloading the same display method (String s) and display (Object o) when passing null in a method from the main method, why is display (String s) called?
package polymorphism;
/*
* @author Rahul Tripathi
*/
public class OverLoadingTest {
/**
* @param args
* @return
*/
static void display(String s){
System.out.println("Print String");
}
static void display(Object s){
System.out.println("Print Object");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
OverLoadingTest.display(null);
}
}
Output:
Print String
IN above programs when overload the same method display(String s )
and display(Object o)
when pass null
in a method from the main method is called only display(String s )
. Why not name it display(Object o)
?
source to share
In java, when multiple overloaded methods are present, java looks for the closest match first. He tries to find the following:
-
Exact math by type
-
Superclass type matching
-
Converting to a more primitive type
-
Convert to stand-alone type
So, in your overloaded method, the String class is a subclass of the object class.
source to share