• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Why instantiate a static inner class?  RSS feed

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In reading the Sun Certified Java Essentials link from the Programmer Certification forum, I wondered if there was a case where you would want to instantiate a static nested class instead of just referencing it. For example, I have created an instance of the nested class below as well as a reference variable. Both call MethodA and return the correct result. Is there a case where you would ever instantiate a static nested class rather than just referring to it?

 
author and iconoclast
Posts: 24203
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chris,

The difference between a static nested class and an inner class is that the inner class has an "enclosing instance" -- an instance of the outer class that acts as its parent. A static nested class doesn't have one of these. That doesn't mean that it can have only static methods, as you've shown here: it just means that the class is not associated with a specific paren object.

If you had a Car class with a static nested class Wheel, the Car could include an array of four Wheel objects as a member variable. The Wheels wouldn't each contain a reference to the Car they were attached to -- but if they don't need one, then making Wheel a static nested class rather than an inner class saves a small amount of memory, and perhaps more importantly saves the cpu time it would take to initialize that enclosing instance reference.

Make sense?
 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. The Car/Wheel analogy brings it home. I did not try adding non-static methods to the static inner class but will to ensure I understand that if I need the existence of an enclosing class, I would instantiate the static class rather than just creating a reference variable to it.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!