• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final instance variables

 
geeta rai
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an instance variable is declared final and is not initialized, wouldn't it get the default value?
 
prasanthi alla
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
it gives compile time error i think
 
mrudul joshi
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic