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

}

}
有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top