Anonymous Class

What is anonymous class? What is its use in Java?

Questions by Reshma1

Showing Answers 1 - 1 of 1 Answers

Gautam saini

  • Jul 15th, 2011
 

An anonymous class is a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator. While a local class definition is a statement in a block of Java code, an anonymous class definition is an expression, which means that it can be included as part of a larger expression, such as a method call. When a local class is used only once, consider using anonymous class syntax, which places the definition and use of the class in exactly the same place.
One of the most elegant things about anonymous classes is that they allow you to define a one-shot class exactly where it is needed.
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 cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.
Since 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 constructor. In fact, instance initializers were introduced into the language for this very purpose.

In general, you should consider using an anonymous class instead of a local class if:
The class has a very short body.
Only one instance of the class is needed.
The class is used right after it is defined.
The name of the class does not make your code any easier to understand.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions