I’ve been coming across this code several times and I would like to know what it means or what it is equivalent to:
A a = new A() {
// declare some methods and whatever
};
What does the above mean? What is it equivalent to (if it is equivalent to anything)?
They’re declaring an anonymous class. Class
Ais (likely) either an interface or an abstract class that must have implemented methods in order to be a subclass ofA. Java allows you to define those methods on the fly with anonymous classes.For example, there is only one method to implement for
ActionListener, which isactionPerformed(ActionEvent). Many times it’s easier to define that method in an anonymous class like so:Edit in response to the OP’s comment
You could certainly create a class file for an
ActionListenerand create a new instance of your class instead of creating an anonymous class. That is, assuming you could do everything you needed to do in a separate class. Many times anonymous and inner classes are defined so that you can have access to the outer class’s fields and methods. It is also many times more object oriented to define an inner or anonymous class if the the inner class “belongs” to the outer class and to no one else.