Inner Class in JAVA
(You can learn about Static Nested Class here )
(You can learn about Non-Static Nested Class here )
(You can learn about Local class here)
4.Anonymous Class
Definition: An anonymous class is a type of inner class that does not have a name(an anonymous class is a special type of nested class that doesn’t have a name). It is typically used for one-time use, such as implementing an interface or extending a class, without the need to create a separate named class.
Get BansodThomas’s stories in your inbox
Join Medium for free to get updates from this writer.
Declaration: In Java, an anonymous class is defined and instantiated simultaneously, usually when required. The basic syntax for defining an anonymous class is as follows:
new <InterfaceName>() {
// Anonymous class body
// This can include method implementations, field declarations, etc.
}or
new <SuperclassName>(<arguments>) {
// Anonymous class body
// This can include method implementations, field declarations, etc.
}example of an anonymous class that implements an interface:
public class Main {
public static void main(String[] args) {
// Create an instance of the interface using an anonymous class
MyInterface myInterface = new MyInterface() {
@Override
public void myMethod() {
System.out.println("Anonymous class implementing MyInterface");
}
};
// Call the method defined in the interface
myInterface.myMethod();
}
// Define a simple interface
interface MyInterface {
void myMethod();
}
}Use Case:
GUI Development: When using anonymous classes in GUI development, event handling is a typical use case. For instance, you may establish event listeners for buttons or other components in Java Swing by using anonymous classes.
example:
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
// Create a button
JButton button = new JButton("Click Me");
// Add an action listener using an anonymous class
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});
// Add the button to the frame
frame.add(button);
// Set frame size and make it visible
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}




