如果最终变量是在参数化构造函数中动态初始化的,则它将破坏最终规则

问题描述

如果最终变量在参数化构造函数中初始化,并且数据是通过构造函数args分配的,那么每个对象的最终值似乎都在变化。

public class Test {
  final int k;
  Test(int i){ this.k=i;}
  public static void main(String[] args) {
    for(int i=1;i<=5;i++){
    Test t= new Test(i);
    System.out.println(t.k);}
  }
}

最终变量是不是仅在实例级别或在所有实例级别都不能更改的变量,它应该是常量吗?

解决方法

将最终变量分配给实例。 如果创建Test类的多个实例,则它们将具有自己的最终变量版本。 如果最终变量是静态的,则将为所有实例设置一次。

,

在您的代码中,您正在创建Test的五个单独的实例,每个实例都有自己的实例变量k。要看到它们是不同的,您可以将代码修改为以下形式:

public class Test {
  final int k;
  Test(int i){ this.k=i;}

  public static void main(String[] args) {
    Test[] tests = new Test[5];
    for(int i=0; i<tests.length; i++){
        tests[i] = new Test(i+1);
    }
    for (Test t : tests) { 
        System.out.println(t.k);
    }
  }
}

输出:

1
2
3
4
5