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;                    //
    }                                                //
}

私がしたいのは、Dialogが、Dialogのインスタンスを所有するクラスに実装されているメソッドhit()を呼び出せるようにすることです。IntelliJ IDEAを使用していますが、「非静的メソッドヒットは静的コンテキストから参照できない」と表示されます。
すべては、ゲームのコンテキストに応じてシーケンスオブジェクトのインスタンスを作成するアプリケーション内で実行されるため、ヒットはシーケンス内の非静的オブジェクトを参照する必要があります。

4

3 に答える 3

2

は静的メソッドではないため、呼び出すにhit()は、の囲んでいるインスタンスにアクセスする必要があります。RavelSequence

ネストされたクラスである場合は、thisキーワードifを使用してこれを行います。Dialog

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

RavelSequenceそれ以外の場合は、のインスタンスをインスタンスに渡す必要がありDialogます。

于 2012-06-20T13:19:52.877 に答える
2

あなたはDialogオブジェクトであり、それがどの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();
    }
}
于 2012-06-20T13:24:15.500 に答える
0

RavelSequenceの実装のインスタンスが必要です。RavelSequenceは抽象的であるため、直接インスタンス化することはできません。

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

        if (somethingHappens)
            RavelSequence  ravel = new OutOfBattleSequence(); // we choose implementation
            ravel.hit();
    }
}
于 2012-06-20T13:23:21.870 に答える