• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

RHE Chapter 6, Question 9

 
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
Have a look at this question, and tell me if it's true. I think I'm being mislead.
public class Outer
{
public int a = 1;
private int b = 2;
public void method(final int c)
{
int d = 3;
class Inner
{
private void iMethod(int e)
{
}
}

}
}
Which vars may be referenced correctly in iMethod(int e)?
I believe that classes within methods can only see final variables of the enclosing method, and enclosing class.
Therefore my answer is c and e
the ans given is a, b, c, e
Awaiting your comments.
Cheers
Brian
 
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answers given are correct. An nonstatic inner class can also access the variables in an outer class even if that inner class is declared in a method, as far as I know.
 
Brian, Cavanagh
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah, you're right,
tried out the code, and it's fine
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi! Brian
The given answer is correct.You are not being mislead. The access rules for Local classes ( classes defined inside a block) are:
- you can access final local variables, final method parameters
- A non-static local class can access members defined in the enclosing class ( this is the case in the code you have) - note here - Static local classes can only directly access static members defined in the enclosing class.
I will try and get you JLS specification on this shortly as I am a little short on time right now.
Latha
 
Brian, Cavanagh
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Latha
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic