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

616 views Asked by At

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.?

2

There are 2 answers

2
Aneesh On

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.

0
Ted Hopp On

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