在 Java 类中可以或不可以有内部接口是否有充分的理由?(就像你会一个内部类)。我无法通过 Google 找到明确的答案,但您似乎无法像使用内部类一样嵌入接口。我的猜测是 Java 的创建者没有看到一个很好的理由让它成为可能,所以它不是,但也许真的有很好的理由?
例如我无法编译它(这都是一个大类)
package buttonGetSourceObject;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ClassWithButton implements ActionListener, ButtonOwner{
private String objectName = "";
public ClassWithButton(String string) {
objectName = string;
JFrame f = new JFrame();
JPanel p = new JPanel();
MyJButton b = new MyJButton(this,"Press This Button for Name of Owner of Button");
b.addActionListener(this);
f.add(p);
p.add(b);
f.pack();
f.setVisible(true);
}
public static void main(String[] args){
ClassWithButton c = new ClassWithButton("object1name");
}
@Override
public void actionPerformed(ActionEvent arg0) {
((ButtonOwner)((MyJButton)arg0.getSource()).getOwner()).printInstanceName();
}
public interface ButtonOwner {
public void printInstanceName();
}
private class MyJButton extends JButton {
/**
*
*/
private static final long serialVersionUID = 1L;
Object owner = null;
public Object getOwner() {
return owner;
}
public void setOwner(Object owner) {
this.owner = owner;
}
public MyJButton(Object o, String string){
owner = o;
this.setText(string);
}
}
@Override
public void printInstanceName() {
System.out.println(this);
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public String toString(){
return this.getObjectName();
}
} //end
编译器似乎根本无法识别内部接口“ButtonOwner”存在