[英]Superclass and Subclass Java
I have my superclass called "BossCraft" which includes a void method labeled "move". 我有一个名为“ BossCraft”的超类,其中包括一个标记为“ move”的void方法。 I also have a class that extends BossCraft called SharkBoss, which also has a void "move" method.
我还有一个扩展BossCraft的类SharkBoss,它也具有无效的“移动”方法。
Is it possible to somehow call the SharkBoss's "move" method into the higher BossCraft method? 是否可以以某种方式将SharkBoss的“移动”方法称为高级BossCraft方法?
public class BossCraft
{
public void move
{
//SharkBoss's move should go here
}
}
public class SharkBoss extends BossCraft
{
public void move
{
...
}
}
Yes, super.move()
( super.
means calling (a method of) the superclass) 是的,
super.move()
( super.
表示调用超类的方法)
If you want to do the reverse - call the subclass from superclass - it's not possible. 如果您想做相反的事情-从超类调用子类-这是不可能的。 The superclass does not know (and should not know) of the existence if its subclasses.
如果超类是其子类,则不知道(也不应该知道)存在。
Note that your definitions are syntactically incorrect - you should have brackets - move()
请注意,您的定义在语法上是错误的-您应该使用方括号
move()
use 采用
super.move();
It will call the move() function of its parent (ie its superclass-instance)! 它将调用其父级的move()函数(即其超类实例)!
我想调用父级方法,用户超级关键字如果要调用子级方法,我将看一下Abstract类
Yes: 是:
BossCraft craft = new SharkBoss();
// Actually calls SharkBoss.nove
craft.move();
You should not be doing this. 您不应该这样做。 The whole point of inheritance is that SharkBoss is always a BossCraft, but a BossCraft may or may not be a SharkBoss.
继承的全部要点是SharkBoss始终是BossCraft,但是BossCraft可能是也可能不是SharkBoss。 Methods on the SharkBoss craft should only be applicable to a SharkBoss.
SharkBoss工艺上的方法应仅适用于SharkBoss。
If you call 'move' on a SharkBoss then the SharkBoss move will be called without you having to do anything. 如果您在SharkBoss上调用“移动”,则无需进行任何操作即可调用SharkBoss的动作。
You could simply cast to SharkBoss in the move method of the superclass : 您可以简单地将父类的move方法转换为SharkBoss:
public class BossCraft {
public void move(){
//SharkBoss's move should go here
SharkBoss s = (SharkBoss) this;
s.move();
}
}
However the very principle of using subclasses is that it should be a one-way relationship, superclasses shouldn't know about their subclasses. 但是,使用子类的基本原则是它应该是单向关系,超类不应该知道其子类。 I would advise you to refactor.
我建议您重构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.