• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Why the variable should be declared as final?

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Very nice, Peter! Thanks!
 
Lalit Kapoor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Peter. This is the best explaination i can ever get for this.
 
reply
    Bookmark Topic Watch Topic
  • New Topic