Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why I must use final modifier

 
Jimsecond Huang
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Just test some code below,


public static void main(String[] args){
final HelloWorldSwing hws = new HelloWorldSwing();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
hws.createAndShowGUI();
}
});
}
The ide ask me to add final modifier for variable hws. I don't know why this is mandatory.

anyone knows

Thanks
 
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
Because hwe is a local variable, the stack frame it's defined in may not even exist by the time the run() method is actually invoked. My making the variable final, you're actually giving Java permission to take a copy of the variable's value at the time the inner class object is created, and use that copy, rather than having to go find a (possibly non-existent) value when the run() method runs.
 
Jimsecond Huang
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest,

Thanks so much. I just think I got it but your answer is so perfect.

Jim
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic