2010-06-07 111 views
0

您可以将对象转换为实现接口的对象吗?现在,我正在构建一个GUI,我不想一遍又一遍重写确认/取消代码(确认弹出窗口)。你可以将一个对象转换为一个实现接口的对象吗? (JAVA)

所以,我想要做的是写一个被传递它在使用该类并告诉是否用户按下确认或取消一类。 总是实现一定的接口。

代码:

class ConfirmFrame extends JFrame implements ActionListener 
{ 
    JButton confirm = new JButton("Confirm"); 
    JButton cancel = new JButton("Cancel"); 
    Object o; 

    public ConfirmFrame(Object o) 
    { 
     // Irrelevant code here 
     add(confirm); 
     add(cancel); 
     this.o = (/*What goes here?*/)o; 
    } 

    public void actionPerformed(ActionEvent evt) 
    { 
     o.actionPerformed(evt); 
    } 
} 

我意识到,我可能过于复杂的东西,但现在我已经碰到这个跑,我真的想知道,如果你可以投一个对象到另一个对象实现一定的接口。

+0

你应该使用接口的所有类实现的,而不是对象,甚至更好地利用泛型,而不是对象。 – 2010-06-07 03:42:46

回答

3

你可以施放对象向上或向下的类型层次;有时这是安全的,有时不是。如果您尝试将变量转换为不兼容的类型(即试图说服编译器确实不是这样),您将得到一个运行时异常(即错误)。更常见的类型(如将ActionListener更改为Object)称为上传,并且始终是安全的,假设您正在投射的类是当前类的祖先之一(并且Object是所有类的祖先之一使用Java)。转到更具体的类型(如从ActionListener转换为MySpecialActionListener)仅适用于您的对象实际上是的更具体类型的实例。

因此,就你而言,听起来像你想要做的是说ConfirmFrame实现了ActionListener接口。我认为该接口包括:

public void actionPerformed(ActionEvent evt); 

然后在这里,在你实现虚拟方法,你要委派EVT到任何物体o被传递到构造函数。这里的问题是Object没有一个叫actionPerformed的方法;只有一个更专业的类(在这种情况下,执行ActionListener就像你的ConfirmFrame类)。所以你可能想要的是该构造函数采取ActionListener而不是Object

class ConfirmFrame extends JFrame implements ActionListener 
{ 
    JButton confirm = new JButton("Confirm"); 
    JButton cancel = new JButton("Cancel"); 
    ActionListener a; 

    public ConfirmFrame(ActionListener a) 
    { 
     // Irrelevant code here 
     add(confirm); 
     add(cancel); 
     this.a = a; 
    } 

    public void actionPerformed(ActionEvent evt) 
    { 
     a.actionPerformed(evt); 
    } 
} 

当然,更多的解释变量名不是“O”或“A”可能会帮助你(和其他人阅读本)明白,为什么你传递一个ActionListener到另一个的ActionListener。以上回答的

+0

感谢您的详细解释:D – exodrifter 2010-06-07 04:03:32

0

当然你可以 - 通常的铸造语法适用。您甚至可以将参数类型声明为接口而不是Object

编辑:当然,变量的类型也需要是接口,或者可以在调用它的方法时进行转换,例如,

ActionPerformer o; 
... 
this.o = (ActionPerformer)o; 

((ActionPerformer)this.o).actionPerformed(evt); 
+0

所以,你会这样做:“this.o =(ActionListener)o;”?我早些时候尝试过,但未找到方法actionPerformed()。 – exodrifter 2010-06-07 03:41:52

+1

Ohhhhh,等等,修正。它找不到它的原因是B/C我把对象初始化为对象而不是接口。谢谢你,Evgeny:D – exodrifter 2010-06-07 03:43:27

0

实例应用::)

class MyFrame extends Frame{ 



     ActionListener confirmListener = new ActionListener(){ 

       //implementation of the ActionListener I 
        public void actionPerformed(ActionEvent e){ 

          if (e.getActionCommand().equals("Cancel")){ 
           // do Something 
          } 
          else if(e.getActionCommand().equals("Confirm")){ 
          // do Something 
         } 
        } 
     }; 

     ConfirmFrame confirmDialog = new ConfirmDialog(confirmListener); 

     //code that uses the ConfirmFrame goes here.... 

} 
相关问题