Search code examples
javavariadic-functionsambiguous

How is the Java compiler able to distinguish between those two constructors/methods?


public class MyClass {

    private String string;
    private Object[] objects;

    // constructor 1
    public MyClass(String string, Object... objects) {
        this.string = string;
        this.objects = objects;
    }

    // constructor 2
    public MyClass(String string) {
        this.string = string;
    }

    public static void main(String[] args) {
        MyClass myClass = new MyClass("foobar");
    }

}

In that case, how did the Java compiler decide to use constructor 2 instead of constructor 1? Why no The constructor ... is ambiguous or a similar error occurs?

PS: the question works with classic methods too.


Solution

  • It's always the most specific method that is called.

    new MyClass("foobar");
    

    searches to call that constructor which takes an object of type String as it's only argument.

    and, var-args method will be used iff matching non-var-args method doesn't exist.