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

Difference between static final variable and instance final variable

 
vanlalhmangaiha khiangte
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me the difference between static final variable and instance final variable with an example and how values are assigned to these variables?
 
Jeremy Botha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One is static and thus bound to the class itself, the other is local to each object of the defining class that is instantiated.

And they're both initialised in the same manner.



J
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some examples of different uses:

Math.PI is declared static final because the value of pi will never change for the life of the entire class. It will never change for any instance you make.

If you have a variable that won't change over the life of an instance of the class you could make that final but non-static. For example, if you have an Employee class, you could make the employeeId field (or anything that seldom changes) final, because it will be different for each instance but shouldn't change once it's been set.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic