从类扩展时何时在方法中使用super或override?

时间:2018-05-12 10:24:52

标签: java inheritance

您好我是java的新手,我目前有两个类(useForce和Attack)工作正常,但这两个类共享了很多代码。为了减少重复的代码,我扩展了使用Force类的Force类但是我不确定如何修改代码?

例如在我的attack.java

if set of numbers generated is higher
require user to input bigger number
userMarks = userMarks + 1

但是我的useForce.java中的两个方法是

public class Attack extends SWAffordance implements SWActionInterface {
         some code here...

@Override
public boolean canDo(SWActor a) {
    SWEntityInterface target = this.getTarget();
    return !a.isDead() && target.getHitpoints()>0;
}

   @Override
public void act(SWActor a) {
    SWEntityInterface target = this.getTarget();
    boolean targetIsActor = target instanceof SWActor;
    SWActor targetActor = null;
    int energyForAttackWithWeapon = 1;//the amount of energy required to attack with a weapon

    if (targetIsActor) {
        targetActor = (SWActor) target;
    }

正如你可以看到这两个在act方法中共享许多类似的代码行,除了在Attack.java中int energyForAttackWithWeapon = 1而在useForce int energyforAttackWithWeapon = 2 ... 如何使用super或override来减少重复代码的行?任何帮助都将受到赞赏。

编辑:如果我使用第三方类来提取重复的代码,我该怎么做,因为攻击已经从SWAffordance延伸了?

1 个答案:

答案 0 :(得分:0)

The template method pattern有助于解决您的重复问题 它允许在基类中定义通用算法,同时让子类自定义算法的某些部分。

因此,要定义常见的具体操作和自定义操作,以便在抽象类中定义子类:AbstractAttack

public abstract class AbstractAttack extends SWAffordance implements SWActionInterface {

    public abstract int getEnergyForAttack();
    public abstract boolean canDo(SWActor a);

    public void act(SWActor a) {
        SWEntityInterface target = this.getTarget();
        boolean targetIsActor = target instanceof SWActor;
        SWActor targetActor = null;
        int energyForAttack = getEnergyForAttack();
        ... // use  energyForAttack 
        if (targetIsActor) {
            targetActor = (SWActor) target;
        }
    }


}

现在Attack和其他子类继承自AbstractAttack,以便从具体操作中受益,并实现他们自己的特性:

public class DefaultAttack extends AbstractAttack  {

   @Override
   public boolean canDo(SWActor a) {
       SWEntityInterface target = this.getTarget();
       return !a.isDead() && target.getHitpoints()>0;
   }

   @Override
   public int getEnergyForAttack(){
        return 1;
   }
}

public class UseForce extends AbstractAttack  {

   @Override
   public boolean canDo(SWActor a) {
      return a.getForcepoints()>=minUsePoints;
  }

   @Override
   public int getEnergyForAttack(){
       return 2;
   }
}