在Java中初始化最终字段

我有一个有很多最终成员的类,可以使用两个构造函数之一进行实例化。 构造函数共享一些代码,这些代码存储在第三个构造函数中。

// 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); } 

问题是这段代码无法编译: Variable 'two' might not have been initialized. 有人可能会从MyClass中调用第一个构造函数,然后新对象将没有“两个”字段集。

那么在这种情况下,在构造函数之间共享代码的首选方法是什么? 通常我会使用辅助方法,但共享代码必须能够设置最终变量,这只能从构造函数中完成。

这个怎么样? (更新了已更改的问题)

 public class MyClass { private final SomeType one; private final SuperType two; public MyClass (SomeType commonArg, int intIn) { this(commonArg, new SubTypeOne(intIn)); } public MyClass (SomeType commonArg, String stringIn) { this(commonArg, new SubTypeTwo(stringIn)); } private MyClass (SomeType commonArg, SuperType twoIn) { one = commonArg; two = twoIn; } } 

您需要确保在每个构造函数中初始化所有最终变量。 我要做的是有一个构造函数初始化所有变量,并让所有其他构造函数调用,传入null或一些默认值,如果有一个字段,他们没有给出值。

例:

 public class MyClass { private final SomeType one; private final SuperType two; //constructor that initializes all variables public MyClas(SomeType _one, SuperType _two) { one = _one; two = _two; } private MyClass(SomeType _one) { this(_one, null); } public MyClass(SomeType _one, SubTypeOne _two) { this(_one, _two); } public MyClass(SomeType _one, SubTypeTwo _two) { this(_one, _two); } } 

您需要做的就是确保初始化“两个”。 在第一个构造函数中,只需添加:

 two = null; 

除非在只调用第一个构造函数的情况下给出一些其他值。

您收到此错误,因为如果您调用了MyClass(SomeType oneIn) ,则不会初始化two