java多个构造函数

时间:2015-09-24 21:54:06

标签: java constructor code-duplication

如果我在一个类中有多个构造函数,我如何避免为所有构造函数初始化的那些字段重复代码,或者这不是更好?

例如:

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时避免重复的代码,或者这个重复的代码是否被视为可接受/更可取?

1 个答案:

答案 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());
  }
}