How does java compiler "most specific method calling rule" work?

ASH :

I'm unable to understand how does java "Choosing the Most Specific Method" rule in function overloading works.

I have a class where function overloading is achieved. There are two functions with the same name "show". Once accepts Object type argument and other accepts String type.

I'm calling the function passing null. The method with String type argument gets called.

class Test
{

    public void show(String s)
    {
        System.out.println("hi");
    }

    public void show(Object o)
    {
        System.out.println("hello");
    }


    public static void main(String s[])
    {
        Test t = new Test();
        t.show(null);
    }
}

The output will be "Hi". Please help me understand the explanation.

jsvilling :

Java will always try to use the most specific version of a method that is available.

The two methods

public void show(Object o) { ... }

public void show(String s) { ... }

could take null as a valid value. In this scenario the overload taking a String parameter is used, because String is more specific than Object.

If you add a third method

public void show(Integer t) { ... }

your code wouldn't compile any more because String and Integer are not related. Neither is more specific than the other and the compile is not able to decide which one to use.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309988&siteId=1