• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

final question...

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic