Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final with static

 
Angela lewis
Ranch Hand
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code works fine


But this gives an error
cannot assign a value to final variable x


Can't get the reason why marking it static gives this error regarding final variable.
 
Sundar Murthi
Ranch Hand
Posts: 209
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Angela

Non-Static(instance) variables are initialized at the time of object creation.so at first one u r not getting error


But in static members, these are initialized at Class loading time itself
So in "static final int x;" x value must known to the compiler at the time of compilation it self.

i hope it will help u
 
Sanyev Babu
Ranch Hand
Posts: 132
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the second case variable x is a class variable. It should be initialized at the time of definition. We can initialize a final instance variable inside the constructor but not class variable. So you will get a compile time error if you try to initialize a final class variable inside a constructor.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a case where a final static member is initialized at class loading time with a value not known at compile time:

 
Chris Allen
Ranch Hand
Posts: 127
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sundar Murthi:
Hi Angela

Non-Static(instance) variables are initialized at the time of object creation.so at first one u r not getting error


But in static members, these are initialized at Class loading time itself
So in "static final int x;" x value must known to the compiler at the time of compilation it self.

i hope it will help u


Going along with Barry's example, the value of static variable is still assigned prior to the class instantiation (it is determined when the class loads since all static block initializers are executed at the time the class loads). Thus, it does not matter that the actual value is known at compile time for the static variable, just that it is assigned when the class loads and before object instantiation (when you class constructor method executes).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic