Java Anonymous Class

In Java, anonymous classes allow you to define a class directly within an expression, without explicitly naming it. They are particularly useful when you need to create a class for a single-use scenario or to implement an interface's methods concisely.

Key Characteristics:

  1. No Name: Unlike traditional classes, anonymous classes don't have a designated name.
  2. Inline Definition: They are defined directly where they are used, typically within an expression or method call.
  3. Extending or Implementing: They can either extend an existing class or implement an interface.
Syntax:

The syntax for anonymous classes involves extending an existing class or implementing an interface, followed by an optional body containing method implementations or member declarations:

new ClassName() { // Optional method implementations or member declarations }; // OR new InterfaceName() { @Override public void interfaceMethod() { // Implementation } };

Here's a detailed explanation with examples:

Anonymous Class for Interface Implementation

interface MyInterface { void myMethod(); } public class Main { public static void main(String[] args) { // Creating an anonymous class to implement MyInterface MyInterface myInterface = new MyInterface() { @Override public void myMethod() { System.out.println("Implementation of myMethod in anonymous class"); } }; // Calling the method defined in the anonymous class myInterface.myMethod(); } }

In this example, we define an anonymous class that implements the MyInterface interface. We provide the implementation of the myMethod() within the anonymous class and instantiate it directly.

Anonymous Class for Abstract Class Extension

abstract class MyAbstractClass { abstract void myMethod(); } public class Main { public static void main(String[] args) { // Creating an anonymous class to extend MyAbstractClass MyAbstractClass myAbstractClass = new MyAbstractClass() { @Override void myMethod() { System.out.println("Implementation of myMethod in anonymous class"); } }; // Calling the method defined in the anonymous class myAbstractClass.myMethod(); } }

Here, we define an anonymous class that extends the abstract class MyAbstractClass. We provide the implementation of the abstract method myMethod() within the anonymous class.

Anonymous Class for Event Handling

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { // Creating a button with an action listener using anonymous class JButton button = new JButton("Click Me"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Button Clicked!"); } }); // Creating a JFrame to hold the button JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(button); frame.setSize(200, 100); frame.setVisible(true); } }

In this example, we create a simple GUI application with a button. We use an anonymous class to define the ActionListener for the button. When the button is clicked, it triggers the actionPerformed() method, which shows a message dialog.

Accessing Local Variables:

Anonymous classes can access final or effectively final local variables from the enclosing scope. This allows them to share data with the implementation they define.

Limitations:

No Static Members: Anonymous classes cannot have static methods or initializers.

Single Instance: Since they are defined inline, only one instance of an anonymous class can be created.

When to Use Anonymous Classes

  1. When you need a short-lived class for a specific task within a method or expression.
  2. To implement interfaces with simple logic concisely.
  3. To provide custom behavior for event listeners or callbacks.

Anonymous Classes Vs. Normal Classes in Java

Here are some of the differences between anonymous classes and normal classes in Java:

  1. Anonymous classes do not have a name.
  2. Anonymous classes are created and used in the same place.
  3. Anonymous classes can only be used once.
  4. Anonymous classes can only extend a class or implement an interface.

Conclusion

Anonymous classes are a powerful tool in Java for creating lightweight, inline classes to handle specific functionality. They enhance code readability and maintainability when used appropriately to avoid creating unnecessary named classes for simple use cases.