• 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

Difference between static inner class and inner class

 
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Can someone please tell me what are the difference between static inner class and inner class? I know both can access the outer class private and protected attributes, but what are the difference between 'static' vs 'non-static'?

And when I should use which one?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A non-static one is "connected" to an instance of the outer class; for example, this code works because each Inner instance is connected to an "Outer" instance:



But if you make Inner static, then this doesn't compile. Inner could still access "i" in an Outer object, but there's not an implicit Outer object as there is in this example. In other words, you can create an instance of a static inner class without ever creating an instane of the outer class, but a non-static one requires such an instance.
 
ying lam
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you.

You said, for the static inner class case:


Inner could still access "i" in an Outer object, but there's not an implicit Outer object as there is in this example



How canit access 'i' in an outer object if the above code you shown won't compile once you make the class 'static inner'.
 
Ernest Friedman-Hill
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by ying lam:
Thank you.

You said, for the static inner class case:


How canit access 'i' in an outer object if the above code you shown won't compile once you make the class 'static inner'.



A static version of Inner could still include code like

Outer o = new Outer();
o.i = 3;

It can still access i, it just doesn't have its own implicit copy of i.
 
reply
    Bookmark Topic Watch Topic
  • New Topic