Java类中接口的实现问题思考

SkyIcon 2017-11-30 01:54:29
最近在编写代码的时候,突然想到一个问题,一个类中某个成员的方法会调用某个接口的实现类,这个时候我见过了两种实现方式(其实不止2种实现),其一是在该方法中直接实现该接口的实现,算是匿名内部类了,代码如下:

public class ActionEventDemo1{
public static void main(String[] args) {
new Paint();
}
}

class Paint{
private JFrame frame = null;
private JButton but = null;
private JTextArea textArea = null;
public Paint(){
frame = new JFrame("ActionEvent事件");
frame.setLayout(new GridLayout(2,1));
but = new JButton("显示");
textArea = new JTextArea();
frame.add(but);
frame.add(textArea);
frame.setSize(400,250);
frame.setLocation(400,400);
frame.setVisible(true);

//按钮事件
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(e.getSource()==but){ //获取事件并判断是否为该按钮事件
String str = "按钮,";
textArea.append(str);
}
}
});
}
}

该类中but.addActionListener()这个方法是javax.swing中JButton自带的一个方法,方法参数是ActionListener接口的实现类,这个是通过方法内来实现该接口的,也就是匿名内部类实现。
还有一个实现方式是按钮的调用方法所在的类实现了ActionListener接口,然后实现一些方法,然后按钮的调用方法参数中用this调用该主类,代码如下:

public class ActionEventDemo2{
public static void main(String[] args) {
new Paint();
}
}

class Paint implements ActionListener{
private JFrame frame = null;
private JButton but = null;
private JTextArea textArea = null;
public Paint(){
frame = new JFrame("ActionEvent事件");
frame.setLayout(new GridLayout(2,1));
but = new JButton("显示");
textArea = new JTextArea();
frame.add(but);
frame.add(textArea);
frame.setSize(400,250);
frame.setLocation(400,400);
frame.setVisible(true);

//按钮事件
but.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==but){ //获取事件并判断是否为该按钮事件
String str = "按钮,";
textArea.append(str);
}
}
}

该类中but.addActionListener(this);通过调用this类,而this类实现了ActionListener接口。
以上两个方式经测试都可以实现功能。
现在我想到了一个问题,在Java思想层面上,怎么分析这两个实现方式呢?当实际代码编写时,该选择哪种方式实现比较好呢?比如:什么情况用第一种方式,什么情况用第二种方式......
求大神帮我解答疑惑。
...全文
126 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
huage 2017-11-30
  • 打赏
  • 举报
回复
两种方式都会可以实现相应的业务,第一种方式一般在私有的时候就这样写,也和你业务紧密相关撒,第二种一般在多个监听都会用到同意端业务时使用撒,这样代码更容易维护

50,528

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧