0

ActionListener 是一个接口,但为什么我可以创建实例对象?

   JButton button = new JButton("Button1");

   ActionListener me = new ActionListener(){
        public void actionPerformed(ActionEvent ae){
            JOptionPane.showMessageDialog(null,ae.getActionCommand());  
        }
    };
    button.addActionListener(me);

或者还有什么?我不知道。请帮我。

4

9 回答 9

6

您在这里看到的称为匿名类:me将分配一个实现ActionListener接口的匿名(未命名)类的实例。

于 2012-08-23T16:23:23.723 回答
4

与 C# 不同,Java 的接口不能规定构造函数。

您在代码中所做的是创建一个扩展的匿名类java.lang.Object(它确实有一个默认构造函数)并实现接口。

于 2012-08-23T16:23:55.697 回答
2

What you have instantiated is an Anonymous Inner Class. In short, it's an in-line way to both define a class that has no name and instantiate an instance of that class in one statement. You'll only ever be able to refer to anonymous inner classes by the super class they implement or extend. In the case of this question, the super class is the ActionListener interface.

When you compile your code, there will be an extra .class file that exists with a name like this: OuterClass$1.class. That is the class file that represents the anonymous inner class you've defined.

If you want to learn more, check out this section in the JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5

于 2012-08-23T16:27:11.657 回答
1

因为您正在使用匿名类实现接口

于 2012-08-23T16:23:49.620 回答
1

ActionListener确实,它本身就是一个接口。

但是,代码中的构造是匿名内部类,这意味着您的接口是由该内部类实现的。

于 2012-08-23T16:24:14.800 回答
1

实际上,您正在创建的是Object.class实现接口的匿名子类。因此,您是从 Object 而非接口“继承”构造函数。

于 2012-08-23T16:24:15.393 回答
1

您没有创建ActionListener. 您正在创建一个实现的匿名类,ActionListener并且您正在提供该实现。

于 2012-08-23T16:24:37.203 回答
1

ActionListener is in fact an interface which can not be instantiated.

However, by defining public void actionPerformed() locally you are allowing the interface to act like a class.

This is legal:

 ActionListener me = new ActionListener(){
      public void actionPerformed(...){...};
 };

This is not:

ActionListener me = new ActionListener();
于 2012-08-23T16:27:25.143 回答
0

1.不能constructorInterfacejava中拥有。

2.这里看到的是一个Anonymous Class,它同时声明和初始化,它必须分别扩展或实现一个类或接口

于 2012-08-23T17:08:41.687 回答