Java Reference
In-Depth Information
As you can see, the syntax for defining an anonymous class and creating an instance
of that class uses the new keyword, followed by the name of a class and a class body
definition in curly braces. If the name following the new keyword is the name of a
class, the anonymous class is a subclass of the named class. If the name following
new specifies an interface, as in the two previous examples, the anonymous class
implements that interface and extends Object .
The syntax for anonymous classes does not include any way to
specify an extends clause, an implements clause, or a name
for the class.
Because an anonymous class has no name, it is not possible to define a constructor
for it within the class body. This is one of the basic restrictions on anonymous
classes. Any arguments you specify between the parentheses following the super‐
class name in an anonymous class definition are implicitly passed to the superclass
constructor. Anonymous classes are commonly used to subclass simple classes that
do not take any constructor arguments, so the parentheses in the anonymous class
definition syntax are often empty. In the previous examples, each anonymous class
implemented an interface and extended Object . Because the Object() constructor
takes no arguments, the parentheses were empty in those examples.
Restrictions on anonymous classes
Because an anonymous class is just a type of local class, anonymous classes and local
classes share the same restrictions. An anonymous class cannot define any static
fields, methods, or classes, except for static final constants. Interfaces, enumer‐
ated types, and annotation types cannot be defined anonymously. Also, like local
classes, anonymous classes cannot be public , private , protected , or static .
The syntax for defining an anonymous class combines definition with instantiation.
Using an anonymous class instead of a local class is not appropriate if you need to
create more than a single instance of the class each time the containing block is
Because an anonymous class has no name, it is not possible to define a constructor
for an anonymous class. If your class requires a constructor, you must use a local
class instead. However, you can often use an instance initializer as a substitute for a
Although they are not limited to use with anonymous classes, instance initializers
(described earlier in “Field Defaults and Initializers” on page 108 ), were introduced
into the language for this purpose. An anonymous class cannot define a constructor,
so it only has a default constructor. By using an instance initializer, you can get
around the fact that you cannot define a constructor for an anonymous class.
Search WWH ::

Custom Search