What Is The Most Important Feature of Java?
What Is The Most Important Feature of Java?
An anonymous class in Java is a class not given a name and is both declared and instantiated in a single
statement. You should consider using an anonymous class whenever you need to create a class that will be
instantiated only once.
Although an anonymous class can be complex, the syntax of anonymous class declarations makes them most
suitable for small classes that have just a few simple methods.
An anonymous class must always implement an interface or extend an abstract class. However, you dont use
the extends or implements keyword to create an anonymous class. Instead, you use the following syntax to
declare and instantiate an anonymous class:
newinterfaceorclassname(){classbody}
Within the class body, you must provide an implementation for each abstract method defined by the interface or
abstract class. Heres an example that implements an interface named runnable, which defines a single
method named run:
runnabler=newrunnable()
{
publicvoidrun()
{
//codefortherunmethodgoeshere
}
};
Here are a few other important facts concerning anonymous classes:
An anonymous class cannot have a constructor. Thus, you cannot pass parameters to an anonymous
class when you instantiate it.
An anonymous class can access any variables visible to the block within which the anonymous class is
declared, including local variables.
An anonymous class can also access methods of the class that contains it.