Sobes.tech
Junior

What are anonymous classes in Java and where can they be applied?

sobes.tech AI

Answer from AI

Anonymous classes in Java are local classes without a name. They are declared and instantiated simultaneously. They are typically used when a one-time implementation of an interface or extension of an abstract or regular class is needed.

Uses of anonymous classes:

  • Event handlers in GUI: Often used to create handlers for button clicks or other user actions.

    // Example with Swing ActionListener
    JButton button = new JButton("Click me");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button clicked!");
        }
    });
    
  • Implementation of interfaces with a single abstract method (SAM interfaces): Before lambda expressions, this was the main way to implement functionality for such interfaces.

    // Example with Runnable
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Thread started");
        }
    }).start();
    
  • Creating objects "on the fly": When you need to quickly create an object with modified behavior from an existing class without creating a separate named class.

    // Example of extending an abstract class
    AbstractList<String> cityList = new AbstractList<String>() {
        private String[] cities = {"Moscow", "Saint Petersburg"};
    
        @Override
        public String get(int index) {
            return cities[index];
        }
    
        @Override
        public int size() {
            return cities.length;
        }
    };
    System.out.println(cityList.get(0)); // Outputs: Moscow
    

Anonymous classes have access to final or effectively final local variables in the scope where they are declared. They cannot have static members and cannot be abstract or final.

What are anonymous classes in Java and where can they… - sobes.tech