如果我在一个类中有多个构造函数,我如何避免为所有构造函数初始化的那些字段重复代码,或者这不是更好?
例如:
class ComparableThing<K extends Comparable<K>> {
private int someField;
private Comparator<K> comparator;
public ComparableThing() {
this.someField = 0;
this.comparator = Comparator.naturalOrder();
}
public ComparableThing(Comparator<K> comp) {
this.someField = 0;
this.comparator = comp;
}
}
有没有办法在初始化someField
时避免重复的代码,或者这个重复的代码是否被视为可接受/更可取?
答案 0 :(得分:1)
您可以链接构造函数。从更具体的构造函数中调用更通用的构造函数。这并不罕见。
class ComparableThing<K extends Comparable<K>> {
private int someField;
private Comparator<K> comparator;
public ComparableThing(Comparator<K> comp) { // more general constructor
this.someField = 0;
this.comparator = comp;
}
public ComparableThing() {
this(Comparator.naturalOrder());
}
}