Get your CodeRanch badge!*
The moose likes Java in General and the fly likes why I must use final modifier Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "why I must use final modifier" Watch "why I must use final modifier" New topic
Author

why I must use final modifier

Jimsecond Huang
Greenhorn

Joined: Dec 03, 2004
Posts: 8
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

Joined: Jul 08, 2003
Posts: 24166
    
  30

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.


[Jess in Action][AskingGoodQuestions]
Jimsecond Huang
Greenhorn

Joined: Dec 03, 2004
Posts: 8
Ernest,

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

Jim
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why I must use final modifier
 
Similar Threads
HelloWorldSwing
what is the purpose for allowing local variables as abstract ?
Problem w/ Compile - possible assistance needed in classpath
My *stupid* questions...
Big problem with Sun online tutorial: Swing