Which constructor is called first while passing null in the class having overloaded constructor?

前端 未结 2 1244
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 08:29

Below is the java class having 3 overloaded constructors :

public class Test {

    public Test(Object i){
        System.out.println(\"Object invoked\");
    }
         


        
2条回答
  •  鱼传尺愫
    2021-02-14 08:59

    Java always chooses the most specific method (or constructor) that would be applicable for the argument you pass. In this case, that's the String constructor -- String is a subclass of Object.

    Think about what would happen if you had

    new Test("some string")
    

    Both the Object and String constructors would be applicable here. After all, the argument is both an Object and a String. However, it is clear that the String constructor will be invoked because it is more specific than the Object constructor and still is applicable given the argument.

    null is no different; these two constructors are still applicable, and the String constructor is still chosen over the Object one for the same reason.

    Now, if there were two equally "specific" constructors present (e.g. if you had an Integer constructor) there would be a compilation error when you call Test(null).

    This is outlined in more detail in JLS §15.12.2:

    The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

    There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

    The explicit process of determining which method is the most specific is outlined in JLS §15.12.2.5.

提交回复
热议问题