Java Reference
In-Depth Information
Listing 3-2. Invoking a static member class's class and instance methods
class SMCDemo
{
public static void main(String[] args)
{
EnclosingClass.EnclosedClass.accessEnclosingClass();
// Output: 1
EnclosingClass.EnclosedClass ec = new Enclosin-
gClass.EnclosedClass();
ec.accessEnclosingClass2(); // Output: 1
}
}
Listing3-2 ' s main() methodrevealsthatyoumustprefixthenameofanenclosed
class with the name of its enclosing class to invoke a class method; for example, En-
closingClass.EnclosedClass.accessEnclosingClass(); .
This listing also reveals that you must prefix the name of the enclosed class with
the name of its enclosing class when instantiating the enclosed class; for example,
EnclosingClass.EnclosedClass ec = new Enclosin-
gClass.EnclosedClass(); .Youcantheninvoketheinstancemethodinthenor-
mal manner; for example, ec.accessEnclosingClass2(); .
Static member classes have their uses. For example, Listing 3-3 ' s Double and
Float static member classes provide different implementations of their enclosing
Rectangle class. The Float version occupies less memory because of its 32-bit
float fields,andthe Double versionprovidesgreateraccuracybecauseofits64-bit
double fields.
Listing 3-3. Using static member classes to declare multiple implementations of their enclosing
class
abstract class Rectangle
{
abstract double getX();
abstract double getY();
abstract double getWidth();
abstract double getHeight();
static class Double extends Rectangle
Search WWH ::




Custom Search