Understanding which constructor is chosen and why

前端 未结 4 1103
庸人自扰
庸人自扰 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 16:16

    To answer your second question (since Jon Skeet has already covered the first), when you have both a String constructor and an Integer constructor the compiler doesn't know what you mean by null in new Demo(null): it could be either a String or an Integer.

    Because String can't be cast to Integer (and vice versa) the compiler gives up and reports the ambiguous error. This is in contrast to the String vs Object choice when you don't have the Integer constructor.

提交回复
热议问题