hey . I don't know why inner classes only can access final local variables? Could you help me?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
hey . I don't know why inner classes only can access final local variables? Could you help me?
Hi, ramclever!
After a little digging, I found this post.
So here's what's going on:
Inner classes behave a little bit differently than variables. Whereas the variables in a method are "cleaned" (removed from the stack, never to be seen again) after the method in which they are contained completes its run, inner classes can, in some cases, remain even after the method has finished, due to the fact that the inner classes are sometimes passed as arguments to other methods that can delay the use of the classes.
As you may see, this could result in a very large problem: an inner class could request the value of a local variable after it has been deleted from the stack! This would not be good at all, so to ensure that the correct value can be used in the inner class, the compiler requires that the local variable(s) in question be final. Marking these variables as final allows Java to, at runtime, create a copy of the variable that can safely passed to the inner class.
Last edited by snowguy13; December 6th, 2012 at 10:36 PM. Reason: Tidying up
Use highlight tags to help others help you!
[highlight=Java]Your prettily formatted code goes here[/highlight]
Using these tags makes your code formatted, and helps everyone answer your questions more easily!
Wanna hear something funny?
Me too.