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)

?

+3


source to share


4 answers


The overloaded method is called based on best / closest match. Object

is a top-level class, which means it will match the latter. So the mapping starts with a method taking a parameter String

as the string can be null

, so it is matched and called.



+2


source


The most uncommon method among matching methods will be chosen. ie, null

both Object and String can be accepted, but since String is also an object, the compiler considers String to be more likely to be null than Object.



+1


source


Since the overloading will happen with the best match in the closet, which is the string, and the object is the last closet, because all the classes that inherit from java.lang.object are on the right, so this happens

0


source


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.

0


source







All Articles