First answer is absolutely correct, but if you really want to have only one constructor for all these cases, you can write something like this:
public Client(String name, Integer age, Integer amount) {
this.name = name;
if (age != null) {
this.age = age;
}
if (amount != null) {
this.amount = amount;
}
}
Usage:
Client c1 = new Client("Smith", null, null);
Client c2 = new Client("Smith", 20, null);
Client c3 = new Client("Smith", null, 100);
Client c4 = new Client(null, 20, 100);
Client c5 = new Client("Smith", 20, 100);
Pay attention that I used wrapper class Integer
instead of int
in constructor arguments because variable of int
type can't be null
.
Also, if you make your setters return this
, you'll simulate kind of named arguments in Java:
new Client().setName("Smith").setAge(20).setAmount(100)