I'm looking for google-able terms. I'm just not sure how to describe this syntax:
JButton myButton = new JButton("Press Me");
myButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("MyButton was pressed.");
}
});
This syntax is new to me. Is there a name for this pattern/technique, and what is it?
Also, a follow up question for extra points :-) Why does this exist? It seems to me that this would result in some pretty cluttered code. Why not just extend ActionListener
?
Forgive me, I meant to ask why you wouldn't implement ActionListener
.
It is called anonymous classing an interface.
Essentially, you are taking the Interface of ActionListener and making an instance that is only known by the class that encapsulates it.
You can't extend ActionListener because it is an interface. Extending a class means inheriting from it, and you can't inherit from interfaces in Java.
Interfaces are more customizable and are more like templates and cannot be standalone classes. Typically, there would be no purpose in having an interface be a standalone class.
As Rohit Jain said: Its an anonymous inner class.
Yes you could implement the ActionListener
interface in a ordinary class in another File. I would prefer to do this when:
An anonymous inner class does not need another file. You have the code, just right there where it is needed, but hinders code reuse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With