When I have a class with multiple constructors where one constructor calls another one (constructor chaining), which constructor should be the one that all the other constructors call eventually?
Here's an example where the "all args" constructor calls the "no args" constructor:
class Goblin {
// always starts at 10
private int strength;
private String name;
public Goblin() {
this.strength = 10;
}
public Goblin(String name) {
this();
this.name = name;
}
}
Here's an example where the "no args" constructor calls the "all args" constructor
class Goblin {
// always starts at 10
private int strength;
private String name;
public Goblin() {
this(null);
}
public Goblin(String name) {
this.name = name;
this.strength = 10;
}
}
The idea is that there should be 1 place where this.strength = 10
and it won't have to be copied. Which of these is best?
private int strength = 10;
. I was just using that logic as a stand-in for potentially more complicate logic, e.g. setting up internal arrays for a hash table implementation that takes acapacity
argument, so we can't simply use an instance initializer there.