How do overloaded methods work?

前端 未结 2 1670
无人共我
无人共我 2020-12-04 01:45
public class Test1  {

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

    public void testM         


        
相关标签:
2条回答
  • 2020-12-04 02:20

    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.

    0 讨论(0)
  • 2020-12-04 02:25

    Adding on to an existing reply, I'm not sure if this is because of a newer Java version since the question, but when I tried to compile the code with a method taking an Integer as a parameter instead of an Object, the code still did compile. However, the call with null as the parameter still invoked the String parameter method at run-time.

    For example,

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

    will still give the output:

    Inside String Method
    

    when called as:

    test1.testMethod(null);
    

    The main reason for this is because String does accept null as a value and int doesn't. So null is classified as a String Object.

    Coming back to the question asked, The type Object is encounter only when a new object is created. This is done by either type casting null as an Object by

    test1.testMethod((Object) null);
    

    or using any type of object for a primitive data type such as

    test1.testMethod((Integer) null);
        or
    test1.testMethod((Boolean) null);
    

    or by simply creating a new object by

    test1.testMethod(new  Test1());
    

    It should be noted that

    test1.testMethod((String) null);
    

    will again invoke the String method as this would create an object of type String.

    Also,

    test1.testMethod((int) null);
        and
    test1.testMethod((boolean) null);
    

    will give a compile time error since boolean and int do not accept null as a valid value and as int!=Integer and boolean!=Boolean. Integer and Boolean type cast to Objects of type int and boolean.

    0 讨论(0)
提交回复
热议问题