2012-06-20 50 views
2

好的,我會首先將代碼放在清晰的位置。抽象類的子類包含無法訪問抽象方法的實現的對象

***編輯: 通過在序列創建時將序列實例傳遞給對話框來解決問題,那麼對話框具有調用的內部引用。

public abstract class RavelSequence { 
    protected Dialog dialog; //every subclass uses one of these objects 
    public abstract void hit(); 
} 

public class BattleSequence extends RavelSequence { 
    public void init(){    //this is the edited fix 
     dialog.setSequence(this);  // 
    }         // 

    public void hit(){ //the effect of a 'hit' in battle 
     doSomething(); 
    } 
} 

public class OutOfBattleSequence extends RavelSequence { 
    public void init(){    //this is the edited fix 
     dialog.setSequence(this);  // 
    }         // 

    public void hit(){ //the effect of a 'hit' outside battle 
     doSomethingElse(); 
    } 
} 

public class Dialog extends Container implements Runnable { 
    private RavelSequence sequence;     //this is the edited fix 
    public void run(){ 
     if (somethingHappens) 
      sequence.hit(); 
    } 
    public void setSequence (RavelSeqence sequence){ //this is the edited fix 
     this.sequence = sequence;     // 
    }            // 
} 

我希望發生什麼是該對話框能夠調用的方法打()在任何一個類擁有對話的情況下實現的。我正在使用IntelliJ IDEA,它告訴我'非靜態方法命中不能從靜態上下文中引用'。
整個事情在一個應用程序中運行,該應用程序根據遊戲的上下文創建Sequence對象的實例,因此命中將需要引用序列中的非靜態對象。

回答

2

你是對話框對象不能知道它是哪個RavelSequence的一部分。所以你試圖做的事情是不可能的。在你的對話框中包含一個RavelSequence,它可以正常工作。

例如

public class Dialog extends Container implements Runnable { 
    protected RavelSequence sequence; 

    public Dialog(RavelSequence sequence) { 
     this.sequence = sequence; // or any other mean to set your RavelSequence: setter, dependency injection... 
    } 

    public void run(){ 
     if (somethingHappens) 
      sequence.hit(); 
    } 
} 
+1

好的,這個工程!看起來這比我想象的要容易得多。我將編輯修改後的代碼到問題中。 謝謝! – sideways8

2

因爲hit()不是一個靜態方法,您需要訪問封閉的RavelSequence實例才能調用它。

你這樣做,通過使用this關鍵字如果Dialog是一個嵌套類:

public abstract class RavelSequence { 
    public class Dialog extends Container implements Runnable { 
     public void run(){ 
      RavelSequence.this.hit(); 
     } 
    } 
    public abstract void hit(); 
} 

否則,你將需要的RavelSequence一個實例傳遞到Dialog實例。

+0

它不會編譯,有人告訴我「ravelSequence.RavelSequence」不是一個封閉類。 – sideways8

0

您需要一個RavelSequence實現的實例。由於RavelSequence是抽象的,因此不能直接實例化。

public class Dialog extends Container implements Runnable { 
    public void run(){ 

     if (somethingHappens) 
      RavelSequence ravel = new OutOfBattleSequence(); // we choose implementation 
      ravel.hit(); 
    } 
} 
+0

BattleSequence和OutOfBattleSequence對象是'正在運行節目',可以這麼說,但是他們需要知道對話何時得到'命中',所以我不認爲創建一個新的序列是可行的。命中需要去具體的BattleSequence或OutOfBattleSequence;無論哪個實例化調用命中的Dialog。 – sideways8

+0

這是一個示例來展示如何創建一個RavelSequence。當然,在事件被解僱之前它必須被立即執行,否則戰略模式是無用的。 – jocelyn

相關問題