Variable argument constructor _may_ conflict, but compiles

前端 未结 2 1505
盖世英雄少女心
盖世英雄少女心 2020-12-11 19:42

I have two constructors that compile just fine but I\'d expect Java to complain about the possibility of ambiguity.

public Foo(int id, Bar bar, String name,          


        
2条回答
  •  一整个雨季
    2020-12-11 20:33

    I agree with you Sean, the following code could be calling any of the two constructors you defined:

    Foo foo = new Foo(3, new Bar(), "", "");
    

    However, when the java people introduced the "variable argument notation", they decided that the above would call "the most especific constructor" defined. In this case I have 2 String arguments, and your first constructor needs exactly 2 String arguments, so it will be called.

    The second constructor will be called only if there are more or less than 2 String arguments, for example:

    Foo foo = new Foo(3, new Bar(), "", "", "");
    

    Or even:

    Foo foo = new Foo(3, new Bar());
    

    I hope that helps to clarify why you don't get the compiler to complain about it (it´s just the way they decided it should work).

提交回复
热议问题