How does constructor overloading work, and how do you avoid writing two constructors that the compiler cannot tell apart?
Constructor overloading means that a class has more than one constructor, and Java picks the right one by looking at the arguments you gave when you called new.
public class Main {
public static void main(String[] args) {
Money a = new Money(1050);
Money b = new Money(10, 50);
System.out.println(a); // 10.50
System.out.println(b); // 10.50
}
}
And the class has two constructors, one that takes a single number and one that takes two.
public class Money {
private final long amountInCents;
public Money(long amountInCents) {
this.amountInCents = amountInCents;
}
public Money(long pounds, long pence) {
this.amountInCents = pounds * 100 + pence;
}
}
And how do you avoid writing two constructors that the compiler cannot tell apart? The rule is that the number of the parameters has to be different, or the types have to be different. If two constructors have the same number and the same types then they have the same signature and the compiler will refuse the class.
// This does not compile. The two constructors have the
// same signature, so the compiler cannot tell them apart.
public Money(long amountInCents) {
this.amountInCents = amountInCents;
}
public Money(long amountInCents) {
this.amountInCents = amountInCents;
}
And there are two kinds of clash that people run into. The first one is the same types, like the example above. The second one is two constructors that look different but are the same after the compiler works out the types.
// These two are the same as far as the compiler is concerned.
public void setAmount(int amount) { }
public void setAmount(long amount) { }
// And so are these two.
public void setAmount(int amount) { }
public void setAmount(Integer amount) { }
So the safe rule is to make the difference obvious. If the types are different then the difference is obvious. And if the number is different then it is obvious too. And if you cannot make it obvious then you have probably designed the class badly.
So the rule to remember is this. The signature has to be different, and it is much better if the difference is obvious to a reader as well.
The next two questions in this topic explain the idea and the parameter order problem.