Understanding which constructor is chosen and why

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

    The fact the String constructor is mentioned in by the compiler in your second error:

    The constructor Demo(String) is ambiguous.
    

    is not significant. This is because the Constructor which takes a String is the first declared constructor, so the compiler uses it in its error message. Change to have the Object constructor first and you get:

    The constructor Demo(Object) is ambiguous.
    

    What it's trying to say is there's ambiguity between the constructor which takes the Integer and the Object, so you have to be more specific, as null can be applied to each. Integer IS-NOT-A String, so the two types are not compatible. You need to be more specific so the compiler can bind the constructor call.

    See @Jon Skeet answer for why the compiler raises an error in some instances and not in others.

提交回复
热议问题