How do overloaded methods work?

前端 未结 2 1681
无人共我
无人共我 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: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.

提交回复
热议问题