• Post Reply Bookmark Topic Watch Topic
  • New Topic

instance final variables  RSS feed

 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In above code sample, compilation fails saying "variable i might not have been inialized"
But when we create an instance of the class testFinal the final variable should get value if its uninitialized.
 
Sheriff
Posts: 21136
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From another thread:
Jesper Young wrote:Please use the code tags correctly; don't double-click the Code button, because it will open and immediately close the code block.


All static and instance variables get automatic values except final ones. You need to provide values for those manually.
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to initialise the final fields before the constructor completes. Thereafter you mustn't reassign them.
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To see what Campbell means, consider the smaller example with the same problem:


'i' is not explicitly assigned a value when an instance of the class is created, and since you are not allowed to alter the value of the final field it is not valid to set the value afterwards. Therefore you need to make sure all constructors assign a value for 'i' when an instance is created.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!