• 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

Inner Classes

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Can someone tell me what the scope of an inner class is which is inside a method of the outer class?
For example, when I tried to instantiate an inner class "I" which is inside the method amethod() of the outer class "O" from another class A (all in the same source file), I get the compiler error " class O.I is not found. Does this mean that an Inner class's scope is only within the method "amethod" ?
class O
{
void amethod()
{
class I
{
}
}
}
class A
{
O.I i = new O().new I();
}

class I doesn't seem to be visible even in the outer class O - What are these Inner classes really used for?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An inner class defined inside a method is a local class. Its scope is limited to the inside of the method only. However, if it implements or extends an interface or class which is defined outside the method, then you can pass an instance of your local class into the outside world. For example, you can create an anonymous (local) class which implements ActionListener, and pass it to some other object using the addActionListner() method.
The main reasons to use local classes are: if the class will only ever be used in a small area, then it makes sense to define it as close to that area as possible. And, local classes can access local variables in the same method, provided they are final - something which non-local classes cannot do. So you may occasionally find this useful.
 
So it takes a day for light to pass through this glass? So this was yesterday's tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic