Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final question...

 
Krep Lock
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no, this isn't the last question i'll be asking, it's a question about the final keyword. the following code snippet stumped me:


i was sure that final locks in a variable's value, but in this program label gets updated every time you click a button.

my guess is that final only locks the reference to the label object, so updating the object itself is fine. but why bother to final the reference in this simple situation?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without seeing more code, it's impossible to say whether "final" is actually doing anything useful. Some people like to use it liberally just to make it clear which variables change and which ones don't, and there's this whole thing with anonymous inner classes which requires the use of local final variables; that one comes up a lot in GUI work, so it might be that.

But in any case, yes: final has no effect at all on an object that a final variable is pointing to; it only affects the variable itself.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Krep wrote:
my guess is that final only locks the reference

Good guess. Marking a primitive variable final means, that it's value has to be assigned once and for all. It cannot be changed afterwards.
Marking an object variable final means, that it cannot be reassigned to another variable. But the object the variable is pointing to may be changed.
See example:




And as Ernest already mentioned: "this whole thing with anonymous inner classes".
A method local inner class can only refer to local variables if they are final.
See second example:



The depicted line will only compile, if variable year is final.
And that may be the cause why your JButton is marked final, as in GUI codes anonymous inner classes are frequently used e.g. for action listeners.


Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic