0

なぜ私の子クラスが正しく継承されないのか疑問に思いました。

もしわたしが持っていたら...

public class ArithmeticOp{

    //some constructor

    public static void printMessage(){
        System.out.println("hello");
    }

}

と別のクラス

public class AddOp extends ArithmeticOp{

    //some constructor

    ArithmeticOp op = new ArithmeticOp();
    op.printMessage();           //returns error
}

私の日食は「トークン「printMessage」の構文エラー、このトークンの後に識別子が必要です」を返し続けます

誰か助けてもらえますか?ありがとう!親クラスからも子クラスからもメソッドを呼び出す他の方法はありますか?本当にありがとう!

4

2 に答える 2

3

これは、クラス本体に任意のコードを入れることができないためです。

public class AddOp extends ArithmeticOp{

    ArithmeticOp op = new ArithmeticOp(); // this is OK, it's a field declaration
    op.printMessage();                    // this is not OK, it's a statement
}

op.printMessage();メソッド内、または初期化ブロック内にある必要があります。

それはさておき、あなたのコードは間違っていると感じます。独自のサブクラス のArithmeticOp 内部をインスタンス化するのはなぜですか?

于 2011-05-08T13:58:09.693 に答える
0

これは、そのメソッドが静的として宣言されているためです。私は間違っているかもしれませんし、私がそうなら誰かがコメントすると確信していますが、あなたはできると思います:

public class AddOp extends ArithmeticOp{

    //some constructor

    ArithmeticOp op = new ArithmeticOp();
    super.printMessage();           //super should call the static method on the parent class
}

または

public class AddOp extends ArithmeticOp{

    //some constructor

    ArithmeticOp op = new ArithmeticOp();
    ArithmeticOp.printMessage();           //Use the base class name
}
于 2011-05-08T04:33:13.857 に答える