Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why the variable should be declared as final?

 
Lalit Kapoor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very nice, Peter! Thanks!
 
Lalit Kapoor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Peter. This is the best explaination i can ever get for this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic