I have a class with lots of final members which can be instantiated using one of two constructors. The constructors share some code, which is stored in a third constructor.
// 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);
}
The problem is that this code doesn't compile: Variable 'two' might not have been initialized.
Someone could possibly call the first constructor from inside MyClass, and then the new object would have no "two" field set.
So what is the preferred way to share code between constructors in this case? Normally I would use a helper method, but the shared code has to be able to set final variables, which can only be done from a constructor.