Instantiating Anonymous Classes – Nested Type Declarations

Instantiating Anonymous Classes

The discussion on instantiating local classes (see Example 9.12) is also valid for instantiating anonymous classes. The class AnonClassClient in Example 9.14 creates one instance at (11) of the non-static anonymous class defined at (5) by calling the non-static method createShape() on an instance of the class Painter, and two instances at (12) and (13) of the anonymous class that is defined in static context at (8) by calling the static method createDrawable() in the class Painter. The program output shows the polymorphic behavior and the runtime types of the objects. Similar to a non-static local class, an instance of a non-static anonymous class has an instance of its enclosing class associated with it. An enclosing instance is not mandatory for creating objects of a static anonymous class.

The names of the anonymous classes at runtime are also shown in the program output in Example 9.14. A numbering scheme ($i) is used to designate the anonymous classes according to their declaration order inside the enclosing class. They are also the names used to designate their respective class files. Anonymous classes are not so anonymous after all.

Referencing Instances of an Anonymous Class

Each time an anonymous class declaration is executed it returns a reference value of a new instance of the anonymous class. Either an anonymous class extends an existing class or it implements an interface. Usually it makes sense to override (and implement) methods from its supertype. References of its supertype can refer to objects of the anonymous subclass. As we cannot declare references of an anonymous class, an instance of an anonymous class can only be manipulated by a supertype reference. Any subclass-specific members in an anonymous class cannot be accessed directly by external clients—the only functionality available is that provided by inherited methods and overridden methods which can be invoked by a supertype reference denoting an anonymous subclass instance.

Leave a Reply

Your email address will not be published. Required fields are marked *