jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes final variables Anonymous Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "final variables Anonymous Class" Watch "final variables Anonymous Class" New topic

final variables Anonymous Class

Neha Mohit
Ranch Hand

Joined: Apr 25, 2006
Posts: 87

This is my first post in the forum, so please disregard the post if i dont make sense.

What i want to know,Why is that the arguments are compulsorily be final?? in an anonymous class.

The book says the "final" restriction is because those variables are on the stack,they can go out of scope before the inner class is done with them. By making them final, the inner class can make a copy of those variables that it uses.

But as far as i know the arguments passed to a function having an anonymous class or any other code will live until the function itself goes out of the scope.

Lets take an example.

class First
void func(int i)
// Some code here

in the above code , i will go out of the scope only when the method func(int) goes out of scope so how can we say they can go out of scope before the inner class is done with them.. hope the scope rule is same for a normal method or method containing an inner class.

Hope someone comes to help ? I am so confused

[ April 25, 2006: Message edited by: Neha Mohit ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


Welcome to JavaRanch!

Consider this (illegal) code in which "x" is not final:

This method starts a thread which sleeps for a while, then prints a local variable's value. After it starts the thread, it loops for a while, incrementing the variable, then returns.

There are two cases to consider. Let's say that the Thread wakes up and prints the variable x while the "while" loop is still running. Then the thread prints some number between 1 and 100000. Everything's fine.

But what if it wakes up after the while loop has completed? Then "foo()" will return. When the thread wakes up, the local variable "x" has gone out of scope. What should happen? Obviously, some kind of an error.

But Java is defined to make this impossible. Local classes don't have any kind of direct reference to a local variable -- they make a copy of the variable when they are created. This avoids the going-out-of-scope problem. For this to appear consistent, the variable has to be final; otherwise, the copy and the original could end up with different values, and that would be very confusing!

[Jess in Action][AskingGoodQuestions]
Neha Mohit
Ranch Hand

Joined: Apr 25, 2006
Posts: 87
Thanks Ernest for the code and explanation.
I agree. Here's the link: http://aspose.com/file-tools
subject: final variables Anonymous Class
It's not a secret anymore!