Sobes.tech
Junior — Middle

Can you explain what anonymous classes are and how they are used in programming?

sobes.tech AI

Answer from AI

Anonymous classes in programming are classes without a name, which are defined and instantiated directly at the point of use. In Java, they are often used to implement interfaces or abstract classes without the need to create a separate named class.

Example of using an anonymous class to handle an event:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button pressed");
    }
});

Here, a new class implementing the ActionListener interface is created without an explicit name, and an instance of it is created immediately. This is convenient for one-time use when you do not need to reuse the class elsewhere.