How java assign value to final attribute

236 views Asked by At

We know that an Array object (array) has a length attribute and it was declared in Java as:

public final int length;

It was declared as final thus no accessor is needed and we cannot change the value of length unless a new array is created.

My question is: I am very curious how did Java implemented the array class such that they are able to assign a value to length when it was declared as final in the first place?

How would the implementation look like?


NOTE: I am not asking how to change an array's length. I am asking how is it implemented such that a final attribute's value could be updated.

3

There are 3 answers

5
Jigar Joshi On BEST ANSWER

It does not change its value, it assigns it once and never changes. Arrays are fixed length per instance and the array assigns a value to the final field in its constructors (as far as it is only once).

0
STaefi On

The answer is a simple rule:

Final member variables of a class must be initialized in one of the following manners:

  1. At the time of declaration:

    public class Foo{
        private final int size = 10;
    }
    
  2. By the end of every constructor of that class:

    public class Bar{  
        private final int size;
    
        public Bar(int n){
            this.size = n;
        }
    
        public Bar(int n, String name){             
            this.size = n;
        }
    
        ...
    }
    

it means that if you have for example 5 different constructors then you must guaranty that the final variables are initialized at the end of executing every single one of them.

Implementation of array classes is something like the above. Once the [] operator is used, an underneath mechanism calls a constructor of that classes and the final variable size is initialized through that constructor and never changes.

This explanations are relatively figurative and not exact, but I hope this would be helpful for clarifying the concept.

Good Luck.

0
user3437460 On

Like what user Jigar Joshi said. An attribute declared as final can be assigned in the constructor.

I will write a simple example here for future interested users. Nontheless, I will still accept his answer.

class Test
{
    public final int val;

    public Test(){
        val = 5;  //This is allowed in Java
    }       
}