简体   繁体   English

Java:用于创建实现接口的类的实例的简写形式

[英]Java: Short form to create an instance of a class that implements an interface

I'd like to use the new operator to create an instance of JPanel that implements ActionListener and directly overrides the actionPerformed method. 我想使用new运算符创建JPanel的实例,该实例实现ActionListener并直接覆盖actionPerformed方法。

I tried 我试过了

JPanel panel = new JPanel implements ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        // ...
    }
};

but that doesn't work because of a syntax error. 但这由于语法错误而无效。

Of course I could just define a new class like JPanelWithActionListener and call this one with new , but is there any way to do it in just one line? 当然,我可以只定义一个新类,例如JPanelWithActionListener并用new调用它,但是有什么方法可以只用一行完成呢?

That is not possible in Java - there is no anonymous type in Java. 在Java中这是不可能的-Java中没有匿名类型。

Your code new JPanel implements ActionListener() { /*...*/ }; 您的new JPanel implements ActionListener() { /*...*/ };代码new JPanel implements ActionListener() { /*...*/ }; is equivalent to this code. 等效于此代码。

class JPanelWithActionListener extends JPanel implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }
}
JPanel panle = new JPanelWithActionListener();

You want to create a new type JPanelWithActionListener without defining a class (so, that class is anonymous). 您想创建一个新的JPanelWithActionListener类型而不定义一个类(因此,该类是匿名的)。

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

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