File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why instantiate a static inner class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why instantiate a static inner class?" Watch "Why instantiate a static inner class?" New topic
Author

Why instantiate a static inner class?

Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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?


[Jess in Action][AskingGoodQuestions]
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why instantiate a static inner class?