Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final instance variable

 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why doesnt the variable gets initalised to 0 when the a object is created? and why is it so that the varibale should be assigned a value before the contrcuotr gets over?
 
Martin Sergeant
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All variables marked final should be initialized. You can initialize them with the default value but you have to do this
explicitly i.e. final int x=0 and not final int x;. With member variables, they do not have to be initialized when they are declared, but must be
given a value in the constructor. If you have multiple constructors or if else blocks you must make sure that the
final variable is given value in all the constructors/blocks (but not necessarily the same value) else you will get a compiler error.

Martin
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final Variable can be initialized in Constructors (in every Constructors). What do you mean by blocks?

Martin Sergeant says....
or if else blocks you must make sure that the
final variable is given value in all the constructors/blocks


Please Explain. Thanks in Advanced!
 
Henry Wong
author
Marshal
Pie
Posts: 21510
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abimaran Kugathasan wrote:
or if else blocks you must make sure that the
final variable is given value in all the constructors/blocks


Please Explain. Thanks in Advanced!


Basically, what Martin is saying is... that all possible paths during construction, whether a branch is taken or not taken, must initialize a final variable, and initialize it only once.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic