Pergunta

How to define abstract methods in abstract class using design patterns while some methods of methods would be possible to override or change it's behavior in child classes? In this example, public abstract class GameCharacter have method attack which should be pattern like (define some of the methods in GameCharacter and some leave empty, to be * overridden* in child classes).

public abstract class GameCharacter{

public void attack(GameCharacter opponent){

while(opponent.hitPoints > 0 && this.hitPoints > 0){

// some abstract method which behavior can be *redefined* 
//if specific class is *overrides* 
// some of this functions
// it should be pattern design

public void doDamageToOpponent{ 

doAttackOne(){ .... }; // cannot change
doAttackTwo(); // can change, be overridden in child class

}

public void doDamageToThis{ // counterattack

doAttackOne(){ .... }; // cannot change
doAttackTwo(); // can change, be overriden in child class

}

}
Foi útil?

Solução

I guess what you want is something like this:

public abstract class GameCharacter{

    protected abstract doAttackTwo();

    protected final doAttackOne() { ... implement here ... }

    ...
}

doAttackTwo() must be implemented by the subclasses, whereas doAttackOne() cannot be overridden.

Outras dicas

If you declare a method as final it cannot be overriden in a subclass. And of course, if you don't give a method a definition any (concrete) subclass must implement it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top