user1052668
user1052668

Reputation:

Superclass and Subclass Java

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
   {
      ...
   }
}

Upvotes: 0

Views: 1059

Answers (6)

Scherrer Vincent
Scherrer Vincent

Reputation: 344

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.

Upvotes: 0

DJClayworth
DJClayworth

Reputation: 26906

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.

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65879

Yes:

BossCraft craft = new SharkBoss();
// Actually calls SharkBoss.nove
craft.move();

Upvotes: 0

Jan Vorcak
Jan Vorcak

Reputation: 20029

I you want to call parent's method, user super keyword If you want to call child's method, I'd take a look at Abstract classes

Upvotes: 0

Willem Mulder
Willem Mulder

Reputation: 14014

use

super.move();

It will call the move() function of its parent (i.e. its superclass-instance)!

Upvotes: 0

Bozho
Bozho

Reputation: 597392

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()

Upvotes: 3

Related Questions