I have my superclass called "BossCraft" which includes a void method labeled "move". I also have a class that extends BossCraft called SharkBoss, which also has a void "move" method.
Is it possible to somehow call the SharkBoss's "move" method into the higher BossCraft method?
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)
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()
use
super.move();
It will call the move() function of its parent (ie its superclass-instance)!
我想调用父级方法,用户超级关键字如果要调用子级方法,我将看一下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. Methods on the SharkBoss craft should only be applicable to a SharkBoss.
If you call 'move' on a SharkBoss then the SharkBoss move will be called without you having to do anything.
You could simply cast to SharkBoss in the move method of the superclass :
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.