java multiple constructors
本问题已经有最佳答案,请猛点这里访问。
如果在一个类中有多个构造函数,如何避免对所有构造函数初始化相同的字段使用重复的代码,或者这样做不可取?
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } } |
在初始化
您可以链接构造函数。从更具体的构造函数调用更通用的构造函数。这并不少见。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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()); } } |