在Java中为静态最终变量赋值

[
  • Java 构造函数

    在Java中为静态最终变量赋值

    在Java中,可以在构造函数或声明中为非静态最终变量赋值。但是,静态最终变量不能在构造函数中赋值; 必须为他们的声明赋予一个值。

    例如,以下程序正常工作。

    class Test {
      final int i;  // i could be assigned a value here or constructor or init block also.
      Tets() {
        i = 10;
      }
    
      //other stuff in the class
    }
    

    如果我们将i定义为静态最终结果,那么我们必须将这个值分配给i。

    class Test {
      static final int i;   // Since i is static final, it must be assigned value here or inside static block . 
      static{
               i=10;   
    }
    
      //other stuff in the class
    }
    

    这种行为很明显,因为静态变量是在一个类的所有对象之间共享的; 如果静态变量是最终的,那么创建一个新对象会改变不允许的静态变量。

  • Java 构造函数
]

转载请保留页面地址:https://www.breakyizhan.com/java/4167.html