File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes final field in a method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "final field in a method" Watch "final field in a method" New topic

final field in a method

salvador rcn
Ranch Hand

Joined: Feb 18, 2004
Posts: 51

"..A class defined within a method can only access final fields of the enclosing method... "

why is this so ? i mean why only the final fields ? what about others ?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Because such a class object can have a lifetime longer than the stack frame of the method that created it, the local variables that existed when the object was created may not exist later in the object's life. Therefore, what the Java compiler does behind the scenes is give the class member variables to hold the values of the final local variables and copies the values of the final locals into the members. This gives the illusion that the object is accessing the final locals of the method, but really it's using its own members, which can last longer than the local variables do. The illusion would be spoiled if you could do this with non-final variables, as when their values changed, the member variables would not.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: final field in a method
It's not a secret anymore!