Win a copy of Getting started with Java on the Raspberry Pi this week in the Raspberry Pi forum!
  • 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Liutauras Vilda
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Piet Souris

Local Inner Class

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Anand, thanks for your explanation. I understand this now.
 
BWA HA HA HA HA HA HA! Tiny ad:
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic