This question has already been answered:

Here is a very simple code:

item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }); 

Everything seems to be easy. And I do not quite understand him. Even a little ashamed of it. In particular, I don’t understand this new ActionListener () statement. Here, after all, there is an operation new and parentheses .. As if we are creating an object. But you can't create an interface object. And then it is clear that an anonymous class is created here, not an object. Please explain why such a strange syntax and what is actually happening here?

UPD: It was written that this question may be a duplicate: Using an anonymous class But they understand what basically happens in the frame new ActionListener () {} And I understood that an object of an anonymous class was created there, I was wondering why the interface name is used for this.

Reported as a duplicate by pavlofff , torokhkun , Athari , Aslan Kussein , Alex on Nov 9 '15 at 10:15 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • I was wondering why the interface name is used for this - the duplicate answer to this question, too, sort of. - pavlofff
  • Ok, so I do not understand the answer. In any case, already figured out. - Alexander Elizarov
  • one
    @pavlofff Maybe the question is a double, but here the answer is more human. - Athari

1 answer 1

When you create a new object, you write:

 new Foo(<parameters>); 

The semicolon at the end is important, you call directly the constructor of the class Foo.

In the case of an anonymous class, you do this:

 new ActionListener() { // Тело нового класса } 

Pay attention to the braces. This is a difference in syntax. Now, by the meaning: in fact, you create a class heir and at the same time call its constructor without parameters, additionally implementing the methods you need in the body. That is, such a one-time class heir.

You could do this in a separate file:

 class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } } 

And then:

 item.addActionListener(new MyActionListener()); 

the meaning would be similar, but in the future you can still create MyActionListener objects, while using an anonymous class you described it, created an object and forgot about its description.

  • 2
    Thank you very much for the detailed answer! That is, it turns out that the implementation is still there, just missing the implements keyword? Well, the class name is not specified. And an anonymous class is created that implements the interface we need and immediately its object, so the syntax for calling the constructor is used? - Alexander Elizarov
  • Yes, that's right :) - iksuy