1

Is there any way in Java to create variables like final that are not initialized inside the constructor, but yet once they are initialized they can never be changed again? My problem is that I get the variable values at different time points and I'd like to create the class before or as soon as I receive the first value.

I've already thought about the obvious solution of keeping a flag for each variable, but I wanted to know if there's anything more efficient than that.

4

2 回答 2

0

初始化此最终变量时,请确保仅在以下构造之一中进行初始化,否则编译器会抛出错误。

  1. 初始化表达式

    public class FinalVariable { // 在实例初始化表达式中,或 while 声明本身 // final = ; 最终 int finalInstanceField = 5;

    }

  2. 实例初始化程序块

    公共类 FinalVariable { final int finalInstanceField;

    {
        // Initialization in instance initializer block
        finalInstanceField = 5;
    }
    
  3. 构造函数块 public class FinalVariable {

    final int finalInstanceField ;
    
    public FinalVariable() {
        // constructor
        finalInstanceField = 7;
    }
    

    }

静态最终变量可以通过两种方式初始化。1.初始化表达式

public class FinalVariable {
    // in the instance initializer expression, or while declaration itself
    // final <type> <variable_name> = <initializer expression>;
    static final int finalStaticField = 25;

}
  1. 静态初始化块

    公共类 FinalVariable {

    static final int finalStaticField;
    
    static {
        finalStaticField = 7;
    }
    

    }

于 2013-05-06T00:53:45.823 回答
0

我可能会按照这里最后一个答案的方式做一些事情。始终使用 setter 设置字段,如果该字段不是默认值(即 null),则不允许对其进行设置。

于 2013-05-06T00:42:15.470 回答