• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why cant we initialize final static var inside constructor  RSS feed

 
ashwin bhawsar
Ranch Hand
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't we initialize a final static variable inside a constructor?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it's final, and so it can only be assigned to once. Initialising in a constructor means that it will be assigned to every time you create an object of that type, because the static variable is shared between each object.

Whereas the non-static variable is separate for each instance, so each one only gets assigned to once, so that's OK.
 
ashwin bhawsar
Ranch Hand
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, got it.
Thanks
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:Because it's final, and so it can only be assigned to once. Initialising in a constructor means that it will be assigned to every time you create an object of that type, because the static variable is shared between each object.

Not only that, but if no instances are created the final field will get no value at all.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!