2010-06-07 48 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.... 

} 
相關問題