Actually, I've got a confusion in Java while implementing action listener event. I can add action listener event by implementing the class with ActionListener and by


But, I came to know this also does the same thing.

someButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent evt) {
              //some code...

But I could not get it. We cannot use new on an interface but it uses it. I get error if I just use try to instantiate the object using new only what I expected but it works when I create a block for it using {} braces. Could somebody please explain it.

1 Answer 1


The second construct that you use is called an anonymous class.

It's both a declaration and instantiation of a class at the same time. Although ActionListener is an interface, you're creating a new instance of a class that implements that interface along with providing an implementation of its methods (in this case, there's only one method in the interface) and then providing that to the addActionListener() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.