在Java中初始化最终字段

Bri*_*don 13 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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

Ric*_*lor 17

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


sca*_*ity 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);
    }
}
Run Code Online (Sandbox Code Playgroud)