Which constructor is chosen when passing null?

前端 未结 3 1975
醉话见心
醉话见心 2021-01-17 23:24

In the following example, I have 2 constructors: one that takes a String and one that takes a custom object. On this custom object a method \"getId()\" exists which returns

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 00:10

    By doing this:

    ConstructorTest test = new ConstructorTest(null);
    

    The compiler will complain stating:

    The constructor ConstructorTest(AnObject) is ambiguous.

    The JVM cannot choose which constructor to invoke as it cannot identify the type that matches the constructor (See: 15.12.2.5 Choosing the Most Specific Method).

    You can call specific constructor by typecasting the parameter, like:

    ConstructorTest test = new ConstructorTest((String)null);
    

    or

    ConstructorTest test = new ConstructorTest((AnObject)null);
    

    Update: Thanks to @OneWorld, the relevant link (up to date at the time of writing) can be accessed here.

提交回复
热议问题