• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local Inner Class

 
Vinny Chun
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a question from the Exam Cram by B.Brogden.
In the following code for a class in which methoda has an inner class, which variables would the statement in line 8 be able to use in place of XX? (Check all correct answers)
public class Base
{
private static final int ID = 3;
private String name;
public void methodA(final int nn)
{
int serialN = 11;
class Inner
{
void showResult()
{
System.out.println("ResultID = " + XX);
}
}
new Inner().showResult();
}
}
a.The int ID in line 2
b.The String in line 3
c.The int nn in line 4
d.The int serialN in line 5
The answers are a, b and c.
According to exam cram: "Local inner classes and anonymous classes can refer to local variables only if they are declared final.". Answer a and c fulfill this rule. However, why does it allow to access to the String in line 3? Please explain.
 
anand raman
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
You are partly right. Local inner/anonymous classes can only access to final LOCAL variables.
They can however access all other variables which are not local to the method. So in this case they can also access the String variable.
Also please note that
private static final int ID = 3 doesnt necessarily have to be static and final to allow access from the local inner class.
Hope this helps
-Anand
[This message has been edited by anand raman (edited December 18, 2001).]
 
Vinny Chun
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anand, thanks for your explanation. I understand this now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic