-2

如果最终变量在参数化构造函数中初始化并且数据是通过构造函数 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);}
  }
}

最终变量是否不能单独在实例级别或在所有实例中更改,它应该是常量。?

4

2 回答 2

0

在您的代码中,您正在创建五个单独的实例,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

于 2020-08-11T18:47:06.113 回答
0

最后一个变量被分配给实例。如果您创建 Test 类的多个实例,它们将拥有自己的最终变量版本。如果最终变量是静态的,那么它只会为所有实例设置一次。

于 2020-08-11T18:37:51.853 回答