File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Local Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Local Inner Class" Watch "Local Inner Class" New topic
Author

Local Inner Class

Vinny Chun
Greenhorn

Joined: Dec 06, 2001
Posts: 24
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

Joined: Jun 06, 2001
Posts: 66
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

Joined: Dec 06, 2001
Posts: 24
Anand, thanks for your explanation. I understand this now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Local Inner Class