我有一个类,其中有许多 final 成员,可以使用两个构造函数之一进行实例化。这些构造函数共享一些代码,该代码存储在第三个构造函数中。
// SubTypeOne and SubTypeTwo both extend SuperType
public class MyClass {
private final SomeType one;
private final SuperType two;
private MyClass(SomeType commonArg) {
one = commonArg;
}
public MyClass(SomeType commonArg, int intIn) {
this(commonArg);
two = new SubTypeOne(intIn);
}
public MyClass(SomeType commonArg, String stringIn) {
this(commonArg);
two = new SubTypeTwo(stringIn);
}
问题在于这段代码无法编译:变量“two”可能未初始化。
有人可能会从MyClass内部调用第一个构造函数,然后新对象将没有设置“two”字段。那么在这种情况下共享构造函数之间的代码的首选方式是什么?通常我会使用辅助方法,但是共享代码必须能够设置final变量,而这只能从构造函数中完成。