我有一个带有很多最终成员的类,可以使用两个构造函数之一实例化这些成员。构造函数共享一些代码,这些代码存储在第三个构造函数中。
// 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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句