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.
In Java, constructors must be called with the same name as the name of the class in which they live, whereas methods can have any name and can be called directly either with a reference to the class or an object reference. Constructors are an exception to this rule.
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object.
In Java, constructors can be divided into 3 types: No-Arg Constructor. Parameterized Constructor. Default Constructor.
A var-args method/constructor will be chosen only if there is no non-var-arg method/constructor. So it is clear that why compiler chooses MyClass(String string)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With