This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
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?
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.
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.