This site requires JavaScript, please enable it in your browser!
Greenfoot back
Razzo
Razzo wrote ...

2012/10/11

Subclasses and Methods

Razzo Razzo

2012/10/11

#
How would I go around making Subclasses do a certain function (from their Parent class) Within their act statement. For example, I want all Subclasses of "Enemy.class" to do validation checks, like, "Am I dead yet?". I know I can just put the function in each act statement, but is their a better way?
danpost danpost

2012/10/11

#
Putting the method in the 'Enemy' class as 'public' or 'protected' will allow all sub-classes to use it (without doing anything else). This is called 'inheritance'. Sub-classes inherit state and behaviour from their super-classes. Please see the Java tutorial page on inheritance.
Razzo Razzo

2012/10/11

#
I understand that, It's just I would like it to force use it. I want to know If I can make anything that inherits "Enemy" HAS to do the method within Enemy. Rather than allowing it to use it.
actinium actinium

2012/10/11

#
You put the method in Enemy class, then all subclass object inheric this method. Like all subclasses of Actor inherit the act(),getWorld(), ect methods. UUPS someone already replied.
actinium actinium

2012/10/11

#
Your last post doesn't make sense, you need to be more specific.
danpost danpost

2012/10/11

#
The only method that will run automatically in a sub-class that is in a super-class is the act() method. DO NOT put an act method in the sub-classes.
Razzo Razzo

2012/10/11

#
Okay then, Thanks for helping. :)
davmac davmac

2012/10/11

#
You could declare the act() method in the Enemy class as 'final', and have it perform whatever check you like before calling another method ("enemyAct()" or whatever you like to call it).
public final void act()
{
    if (! checkDead()) {
        enemyAct();
    }
}

public void enemyAct()
{
    // default implementation does nothing
}
Then subclasses can override the enemyAct method, but not the act method.
You need to login to post a reply.