Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

java - How do overloaded methods work?

public class Test1  {

    public static void main(String[] args)   {
        Test1 test1 = new Test1();
        test1.testMethod(null);
    }

    public void testMethod(String s){
        System.out.println("Inside String Method");     
    }

    public void testMethod(Object o){
        System.out.println("Inside Object Method"); 
    }
}

When I try to run the given code, I get the following output:

Inside String Method

Can anyone explain why the method with the String type parameter is getting called?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

most specific method argument is chosen for overloaded methods

In this case, String is subclass of Object. Hence String becomes more specific than Object. Hence Inside String method is printed.

Directly from JLS-15.12.2.5

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

As BMT and LastFreeNickName have correctly suggested, (Object)null will cause overloaded method with Object type method to be called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...