Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why instantiate a static inner class?

 
Chris Allen
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?

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic