简体   繁体   English

Java - 这些是哪些类型的类; 哪个是匿名内部class?

[英]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:我认为这将是匿名内部 class 的示例:

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

However, I've also seen this described as an anonymous inner class:但是,我也看到过这个描述为匿名内部 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.在第二种情况下,您正在存储对匿名 class 的引用,以便您稍后可以在其上调用一些方法。

Like Richante said, they both are.正如 Richante 所说,他们都是。

Think about it, they both are unnamed and are defined inside another class.想一想,它们都是未命名的,并且定义在另一个 class 中。

Both are actually examples of Anonymous inner class. In First example, anonymous inner class is provided when passing an argument to addActionListener() method.两者实际上都是匿名内部 class 的示例。在第一个示例中,在将参数传递给 addActionListener() 方法时提供了匿名内部 class。 In second example a reference to anonymous inner class is created.在第二个示例中,创建了对匿名内部 class 的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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