| Author |
Final instance variables
|
geeta rai
Ranch Hand
Joined: Sep 18, 2003
Posts: 48
|
|
|
If an instance variable is declared final and is not initialized, wouldn't it get the default value?
|
 |
prasanthi alla
Greenhorn
Joined: Dec 02, 2003
Posts: 15
|
|
hi it gives compile time error i think
|
 |
mrudul joshi
Ranch Hand
Joined: Nov 12, 2003
Posts: 54
|
|
I think it will get the default value,if not initialized.But what is the point indeclaring it as an instance variable then?We can simply make it static variable.
|
 |
mrudul joshi
Ranch Hand
Joined: Nov 12, 2003
Posts: 54
|
|
Hey, I just checked it in a program code. It is giving a compile time error. But I dont know why is it not getting initialized!
|
 |
Vad Fogel
Ranch Hand
Joined: Aug 25, 2003
Posts: 504
|
|
Originally posted by mrudul joshi: Hey, I just checked it in a program code. It is giving a compile time error. But I dont know why is it not getting initialized!
Final instance variables must be initialized by the time the constructor completes. Otherwise, a compiler error occurs. That means, primitives get their values and references point to either real objects on the heap or null. Instance finals can be assigned either where they are declared, or inside the constructors, or inside the instance initializer blocks. To trace the flow of assignment gets trickier when there're several constructors calling each other thru this(). In such a case, make sure that every constructor allows for the finals to become initialized. A special case of final variables initialization is class finals (static fields). They need to be either initialized where they are declared or assigned inside static initializer blocks. Constructors won't do it since, well, these fields have nothing to do with the class instance. Here's a piece of valid code to demo the concept:
|
 |
Vicken Karaoghlanian
Ranch Hand
Joined: Jul 21, 2003
Posts: 522
|
|
|
What Vad said is correct, you should also note that once a 'final' var is assigned a value then there is no way you can change that value.
|
- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
|
 |
 |
|
|
subject: Final instance variables
|
|
|