java动作侦听器:实现vs匿名类 [英] java action listener: implements vs anonymous class

查看:172
本文介绍了java动作侦听器:实现vs匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试教自己的Java,并有一个问题,我到目前为止还没有回答。在我的一些在线阅读中,我发现使用动作监听器的两种方法似乎做同样的事情。但是我想弄清楚一个人的优势/劣势是什么。



最好使用匿名类:

  public MyClass(){
...
myButton.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
// doSomething
}
});
...
}

或者最好在开始时实现的类如下:

  public MyClass()实现ActionListener {
...
myButton。 addActionListener方法(本);

public void actionPerformed(ActionEvent e){
// doSomething
}
...
}


解决方案

这归结为一种风格的事情。两者将在代码中执行完全相同的方式。



单独的类将倾向于将代码放在您的实际方法中更简单,而匿名内部类将为方法中的监听器实现可以使它更清楚它在做什么。



还有一种情况是匿名内部类可以访问创建它们的方法中的最终变量。你不能用预先写的类来实现(尽管你可以将变量传递给控制器​​)​​。



单独的代码是可重用的 - 所以如果你在多个地方有同样的听众,那么这是明确的赢家。


I am trying to teach myself Java and had a question that I wasn't able to answer so far. In some of my reading online I have found two ways of using action listener that seem to do the same thing. But I am trying to figure out what is the advantage/disadvantage of one over the other.

Is it better to use anonymous class like this:

public MyClass() {
...
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            //doSomething
        }
    });
...
}

or is it best to implement at the beginning of the class like so:

public MyClass() implements ActionListener {
...
    myButton.addActionListener(this);

    public void actionPerformed(ActionEvent e) {
        //doSomething
    }
...
}

解决方案

This comes down to a style thing really. Both will perform exactly the same way in code.

The separate class will tend to keep the code inside your actual method simpler, whereas the anonymous inner class brings the code for the listener implementation within the method which can make it clearer what it is doing.

There is also the case that anonymous inner classes can access final variables in the method that creates them. You can't do that with a pre-written class (although you can pass the variables into the controller).

The separate code is re-usable - so if you have the same listener in multiple places then it is the clear winner.

这篇关于java动作侦听器:实现vs匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆