15

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

// 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 内部调用第一个构造函数,然后新对象将没有“两个”字段集。

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

4

4 回答 4

18

这个怎么样?(针对更改的问题进行了更新)

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;
    }
}
于 2013-02-15T23:01:49.470 回答
6

您需要确保在每个构造函数中都初始化所有最终变量。我要做的是有一个构造函数来初始化所有变量,并让所有其他构造函数调用它,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);
    }
}
于 2013-02-15T23:04:29.093 回答
1

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

two = null;

除非在仅调用第一个构造函数的情况下,您想给它一些其他值。

于 2013-02-15T23:01:33.427 回答
0

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

于 2013-02-15T23:03:04.380 回答