Understanding which constructor is chosen and why

前端 未结 4 1089
庸人自扰
庸人自扰 2020-12-03 15:49

Why following program every time prints I\'m string and not I\'m object. or I\'m int.?

public class Demo {

    public         


        
4条回答
  •  北海茫月
    2020-12-03 15:58

    null can be converted to Object or String, but not int. Therefore the second constructor is out.

    Between the conversion to Object or the conversion to String, the conversion to String is more specific, so that's what's picked.

    The JLS section 15.12.2 describes method overload resolution, and I believe the same approach is used for constructor resolution. Section 15.12.2.5 describes choosing the most specific method (constructor in this case):

    The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

    This about the constructor invocation with Object or String arguments - any invocation handled by new Demo(String) could also be passed on to new Demo(Object) without a compile-time type error, but the reverse is not true, therefore the new Demo(String) one is more specific... and thus chosen by the overload resolution rules.

提交回复
热议问题