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 回答