This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
A class defined within a method can access local method variables only if they're final. Otherwise, the inner class object might outlive the local method variables which only exist during the scope of the method and are typically destroyed when the method exits. But if the local variables are final, then the compiler can copy their values into the inner class object.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Jan 12, 2005
final variable are also destroyed after method termination ( i think ) .
Variables don't do anything. Variables are the nouns, methods are the verbs. A final variable is one that cannot be changed unless it's uninitialized when declared, in which case it must be initialized in a constructor or initialization block.
I hope this helps...
Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Joined: Jan 12, 2005
Jeff you got the wrong or my question was not clear . I meant was what a final variable can do for method local inner class that non final variable can't do .
The value of a final variable cannot change, so that value (not the variable) can be integrated into the object as a "constant."
In the example below, x is a local variable that currently holds the value 1. But x is not final, so that value might change later. If a LocalClass object is created, that object might continue to exist after the method has exited. And so if LocalClass had been allowed to use x, then there would be a problem, because x would no longer exist and the object would have no way of knowing whether the value 1 is still valid.
On the other hand, y is also a local variable. But y is final, so its value of 2 cannot change. Now if a LocalClass object is created, it can simply copy the value of y. When the method exits and y is destroyed, that's okay because the object doesn't have to go back to y for its value. The object uses a "hard-coded" value of 2 instead of the variable y.
(With objects, of course, we're talking about references being final. So if refA is final, then refA will always "point" to the same object.)