2013-02-23 138 views
1

我有一个问题,只是出于好奇,这是如何指定的参考参数的方法,并确保该参数必须实现一个接口如何指定参考方法参数实现接口

如ActionListener的方法处理事件 时,当你添加一个ActionListener使用addActionListener方法(ARG)方法 ARG必须是一个实现ActionListener接口 对象的引用的GUI组件的actionPerformed,这就是我的问题 addActionListener方法,方法,如何确保其ARG实现ActionListener接口

JTextField textField = new JTextField();//creating new text field 

TextFieldHandler textFiledHandler = new TextFieldHandler();//object of the handler 

textField.addActionListener(textFieldHandler);//here's my question 
add(textField); 

//creating a nested class 
private class TextFieldHandler implements ActionListener { 
    @Override 
    public void actionPerformed (ActionEvent event) { 
      //do something here 
    }//end actionPerformed 
}//end class TextFieldHandler 

回答

1

所有你需要做的是将参数的类型设置为接口名称,然后该方法将接受对象,只要它们是实现该接口的类型即可。

实施例:

public void methodName(InterfaceName x) {} 

将接受作为参数实现 “InterfaceName中” 的任何对象。

在这种特殊情况下,public void addActionListener(ActionListener l)可确保参数实现接口ActionListener(这是Java如何实现的)。