wood burning stoves 2.0*
The moose likes Java in General and the fly likes Why the variable should be declared as final? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Why the variable should be declared as final?" Watch "Why the variable should be declared as final?" New topic
Author

Why the variable should be declared as final?

Lalit Kapoor
Greenhorn

Joined: Jun 06, 2004
Posts: 20
Consider the following code:
public class Test {
public int x = 99;
private String s = "Hi";
public void method1(){
final int x = 66;
class MyClass{
public float y = 45.9f;
public void method2(){
System.out.println("x = "+x);
}
}
MyClass m = new MyClass();
m.method2();
}
public static void main(String st[]){
Test t1 = new Test();
t1.method1();
}
}
The above code compiles and runs perfectly if final modifier is applied on the variable x defined in the method1() method. If final modifier is not applied, compile time error occurs. If you remove the definition of variable x from method1() method, the programs runs and displays 99, value of outer x variable which is normal.

Why inner class if defined in a method can access only those variable of that method that are declared as final?
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Because of the way inner classes are implemented. The Java language tricks you into thinking that you've got direct access to local variables in method1(). You don't. What happens under the hood is that MyClass gets a private field x. When an instance of MyClass is constructed, this field gets initialised with the current value of x.

The problem is this. If the value of x were allowed to change, the illusion of having direct access to local variables would break down, because MyClass' copy of x get out of sync with the value in the enclosing method. It would be pretty hard to make sense of what is happening. This is why the compiler enforces that x must be final, so the two (or more) copies that exist can never become inconsistent.

- Peter
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Very nice, Peter! Thanks!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Lalit Kapoor
Greenhorn

Joined: Jun 06, 2004
Posts: 20
Thanks Peter. This is the best explaination i can ever get for this.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why the variable should be declared as final?