简体   繁体   中英

Java - Which types of classes are these; which is the anonymous inner class?

I've read several online articles which contradict each other. I thought this would be an example of an anonymous inner class:

button.addActionListener(new ActionListener() {
    public void actionPerfored(ActionEvent e) {
       // do something.
    }
});

However, I've also seen this described as an anonymous inner class:

ActionListener myListener = new ActionListener() { 
    public void actionPerformed(ActionEvent event) {
          // do something.
    }
};
button.addActionListener(myListener);

Which is which, and why? Thank you!

Both of them are. The second one is just assigned to a variable before being added as an action listener.

This is the same as the difference between

myList.add(new String("myString"));

and

String s = new String("myString");
myList.add(s);

it has nothing to do with anonymous classes.

Both are anonymous inner classes. In the second case you are storing a reference to the anonymous class just so that you can call some methods on it later.

Like Richante said, they both are.

Think about it, they both are unnamed and are defined inside another class.

Both are actually examples of Anonymous inner class. In First example, anonymous inner class is provided when passing an argument to addActionListener() method. In second example a reference to anonymous inner class is created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM