内部类中的构造方法(实现接口) [英] Constructors in Inner classes (implementing Interfaces)
本文介绍了内部类中的构造方法(实现接口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何为一个实现接口的内部类编写一个构造函数?我知道我可以做一个全新的课,但我认为有一个方法来做一些这样的事情:
How would I go about writing a constructor for an inner class which is implementing an interface? I know I could make a whole new class, but I figure there's got to be a way to do something along the line of this:
JButton b = new JButton(new AbstractAction() {
public AbstractAction() {
super("This is a button");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
当我输入它时,它不认识AbstractAction方法作为构造函数(编译器要求返回类型)。
When I enter this it doesn't recognize the AbstractAction method as a constructor (compiler asks for return type). Does anyone have an idea?
推荐答案
只需在扩展类名称后插入参数:
Just insert the parameters after the name of the extended class:
JButton b = new JButton(new AbstractAction("This is a button") {
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
此外,您可以使用初始化块:
Also, you can use an initialization block:
JButton b = new JButton(new AbstractAction() {
{
// Write initialization code here (as if it is inside a no-arg constructor)
setLabel("This is a button")
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
这篇关于内部类中的构造方法(实现接口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文