简体   繁体   中英

If final variable is initialized in parameterized constructor dynamically, then it breaks final rule

If final variable is initialized in parameterized constructor and data is assigned through constructor args then final value seems to be changing here for every object.

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);}
  }
}

Is the final variable not changable at instance level alone or across all instance it should be constant.?

The final variable is assigned to the instance. If you create multiple instances of the Test class, they will have their own version of the final variable. If the final variable is static, it will be only be set once for all the instances.

In your code, you are creating five separate instances of Test and each one has its own instance variable k . To see that these are distinct, you can modify your code to something like this:

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);
    }
  }
}

Output:

1
2
3
4
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM