Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final variables Anonymous Class

 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

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

Neha
[ April 25, 2006: Message edited by: Neha Mohit ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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!
 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest for the code and explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic