• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method Local Inner Class  RSS feed

 
velmurugan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

public void method() {
int i = 0;
class Test {
public void print() {
S.O.P(i) // have error
}
}
Test t = new Test();
}

The above method has a inner class Test, which has a method print.
print() method is trying to access the variable "i" in outer method(). <br>But it cant allow to access "i" because it's a local variable for the outer method, it is stored in stack, <br>it vanished after the method finished.


But It will allow if we declare "i" as final.<br>
What is the reason for it?

public void method1() {
final int i = 0;
class Test {
public void print() {
S.O.P(i)
}
}
Test t = new Test();
}
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please take the time to choose the correct forum for your posts. This forum is for questions on JSP.

This post has been moved to a more appropriate forum.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The inner class captures the value of "i" at the time that an instance of the inner class is created. This gives the appearance of having access to the local variable "i". However, the illusion would be broken if "i" was allowed to change, because the inner class instance would not see the change. Hence, you can only use "final" local variables - they cannot change.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!