Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 538
sp00m Avatar asked Oct 29 '12 11:10

sp00m


People also ask

What are the differences between the constructors and methods in Java?

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.

How do constructors work in Java?

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.

What are the different types of constructor in Java?

In Java, constructors can be divided into 3 types: No-Arg Constructor. Parameterized Constructor. Default Constructor.


2 Answers

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).

like image 144
Juvanis Avatar answered Oct 05 '22 18:10

Juvanis


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.

like image 43
Azodious Avatar answered Oct 05 '22 18:10

Azodious