Anonymous Inner Class in Java

An inner class is a class defined within another class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class. An inner class is fully within the scope of its enclosing class. An anonymous inner class is a class that is not assigned any name.
It is important to note that class Inner is known only within the scope of class Outer. The Java compiler generates an error message if any code outside of class Outer attempts to instantiate class Inner. Generally, these are used whenever you need to override the method of a class or an interface.

Example-

public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter(){
public void mousePressed (MouseEvent ev) {
showStatus("Mouse Pressed !!");
}
}
}

In this example init() method calls addMouseListener() method. Its argument is an expression that defines and instantiates an anonymous inner class The syntax new MouseAdapter() {…} indicates to the compiler that the code between the braces defines an anonymous inner class. And that class extends MouseAdapter. This new class is not named but is automatically instantiated when this expression is executed.

Leave a Reply

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