从父类继承方法不起作用
我想知道为什么我的子类没有正确继承。
如果我有...
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
}
我的 Eclipse 不断返回“令牌“printMessage”上的语法错误,此令牌后需要标识符”
有人可以帮忙吗?谢谢!还有其他方法可以从父类以及子类调用方法吗?非常感谢!
I was wondering why my child class isn't inheriting correctly.
if i had...
public class ArithmeticOp{
//some constructor
public static void printMessage(){
System.out.println("hello");
}
}
and another class
public class AddOp extends ArithmeticOp{
//some constructor
ArithmeticOp op = new ArithmeticOp();
op.printMessage(); //returns error
}
my eclipse keeps returning "Syntax error on token "printMessage", Identifier expected after this token"
could someone please help? thanks! are there other ways to call methods from the parent class as well from a child class? thanks a bunch!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您不能将任意代码放入类主体中:
op.printMessage();
需要位于方法内部或初始值设定项块内部。除此之外,你的代码感觉不对。为什么要在它自己的子类之一
ArithmeticOp
内部实例化一个ArithmeticOp
?This is because you can't put arbitrary code into the class body:
The
op.printMessage();
needs to be inside a method, or inside an initializer block.That aside, your code feels wrong. Why would you want to instantiate an
ArithmeticOp
inside one of its own subclasses?这是因为该方法被声明为静态。我可能错了,我相信如果我错了,有人会发表评论,但我认为你可以这样做:
或者
It's because that method is declared as static. I may be mistaken and I'm sure someone will comment if I am but I think you can do:
Or