Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is it called when I override methods during object initialization?

Tags:

java

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?

Update

Forgive me, I meant to ask why you wouldn't implement ActionListener.

like image 376
quakkels Avatar asked Aug 09 '13 13:08

quakkels


2 Answers

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.

like image 57
Kevin Hartnett Avatar answered Nov 14 '22 22:11

Kevin Hartnett


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:

  • I can give this thing a name
  • I would like to reuse it somewhere else

An anonymous inner class does not need another file. You have the code, just right there where it is needed, but hinders code reuse.

like image 20
user573215 Avatar answered Nov 14 '22 22:11

user573215