Certification Objective Static Nested Classes


Certification Objective —Static Nested Classes

We saved the easiest for last, as a kind of treat:)

You'll sometimes hear static nested classes referred to as static inner classes, but they really aren't inner classes at all, by the standard definition of an inner class. While an inner class (regardless of the flavor) enjoys that special relationship with the outer class (or rather the instances of the two classes share a relationship), a static nested class does not. It is simply a non-inner (also called "top-level") class scoped within another. So with static classes it's really more about name-space resolution than about an implicit relationship between the two classes.

A static nested class is simply a class that's a static member of the enclosing class:

 class BigOuter {    static class Nested { } } 

The class itself isn't really "static"; there's no such thing as a static class. The static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.

Instantiating and Using Static Nested Classes

You use standard syntax to access a static nested class from its enclosing class. The syntax for instantiating a static nested class from a non-enclosing class is a little different from a normal inner class, and looks like this:

 class BigOuter {   static class Nest {void go() ( System.out.println("hi"); } } } class Broom {   static class B2 {void goB2() { System.out.println("hi 2"); } }   public static void main(String[] args) {     BigOuter.Nest n = new BigOuter.Nest();   // both class names     n.go();     B2 b2 = new B2();     // access the enclosed class     b2.goB2();   } } 

Which produces:

 hi hi 2 

image from book
Exam Watch

Just as a static method does not have access to the instance variables and non-static methods of the class, a static nested class does not have access to the instance variables and non-static methods of the outer class. Look for static nested classes with code that behaves like a nonstatic (regular inner) class.

image from book



SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net