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.
It’s always the most specific method that is called.
searches to call that constructor which takes an object of type
Stringas it’s only argument.and,
var-argsmethod will be used iff matchingnon-var-argsmethod doesn’t exist.