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

前端 未结 2 1240
伪装坚强ぢ
伪装坚强ぢ 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:50

    The answer is: Test(String) is invoked.

    Why?

    When determining which of a set of overloaded methods will be invoked, the Java compiler will attempt to match the most concrete type. And it will first attempt to match a signature before employing autoboxing. (@arshajii provided a perfect reference into the Java Language Spec on this)

    Here, Object is the most abstract class in the type system. String subclasses from Object and is therefore more specific/concrete.

    The logic behind this is that if you are overloading a method with a more specific-typed parameter, you're likely wanting to do more with that object (when you subclass, you typically add methods). If method signature determination worked the other way (i.e. the more abstractly-typed signature winning; here, Test(Object)), then none of the more concrete signatures would ever get called.

提交回复
热议问题