Android - 如何强制子窗口覆盖具有代码的父方法

时间:2013-01-23 08:32:12

标签: java android inheritance methods

这是场景 - >想象有3个类,我想做点什么:

public class GameObject {
    public void updateBounds() {
        // do something
    }
}

public abstract class Enemy extends GameObject {
    public abstract void updatePosition(){ //<-- this will not compile, 
                                    //but this is what i want to do, to force 
                                    //child to override parent method
        updateBounds();
    }

}

public class Minion extends Enemy {
    @Override
    public void updatePosition() {
        super.updatePosition(); // <-- how do i throw an exception if this line
                                // is not called within this method of the
                                // child?
        // now do something extra that only Minion knows how to do
    }
}
  • 你如何设计Enemy类,以便它有一个方法可以做某事,但是要求每个孩子都要覆盖它?
  • 如何强制孩子(必须覆盖该方法)也调用父方法?

这几乎就像Android的Activity类,它具有onCreate,onStart,onResume等。可选的方法,但如果你使用它,它会强制你调用super。它不能是抽象的,因为我想在调用方法时运行一些代码(仅在父类的方法中)。如果你知道他们是怎么做的话,可以获得奖励积分吗?

4 个答案:

答案 0 :(得分:5)

Android Sources使用一个名为mCalled的布尔值,在准抽象方法实现中设置为true。在您的情况下,将在原始updatePosition()内。

然后,当您想要致电updatePosition()时,请通过以下方式致电:

private void performUpdatePosition() {
    mCalled = false;
    updatePosition();
    if (!mCalled) throw new SuperNotCalledException();
}

updatePosition()看起来像这样

protected void updatePosition() {
    mCalled = true;
    updateBounds();
}

编辑:

现在我考虑一下,android的做法有点圆了。由于对updatePosition()的所有调用都通过了performUpdatePosition(),因此您不再需要在updatePosition()内部使用可以覆盖的代码,但不应该覆盖。

更好的方法是将所需的操作移至performUpdatePosition()

private void performUpdatePosition() {
    updateBounds();
    updatePosition();
}

protected void updatePosition() {
    //Do nothing by default
}

这样被调用者不必担心调用super.updatePosition。如果子类没有覆盖该函数,那么就不会发生任何额外的事情,而如果它们发生了,则覆盖将添加到先前的行为。

答案 1 :(得分:4)

也许您可以在类

中定义基本方法,而不是调用子方法
public void updatePosition()
{
    //do what you need to do before the child does it's stuff
    onUpdatePosition();
    //do what you need to do after the child does it's stuff
}

protected abstract void onUpdatePosition();

这样,当你调用updatePosition()时,孩子必须拥有它自己的onUpdatePosition()并且你知道父母每次都会发生的事情

答案 2 :(得分:-1)

  

你如何设计敌人类,以便它有一个方法   什么,但要求每个孩子都要覆盖它?

为此,需要将父类方法定义为抽象方法,这只是子类知道父类中定义的方法需要在子类中定义的方式。

  

你如何强迫孩子(必须重写方法)   调用父方法?

如果父类是抽象类,则覆盖方法。

答案 3 :(得分:-3)

怎么样

public abstract class Enemy extends GameObject{
    public abstract void updatePositionCommon(){ 
        //code common to all

        updatePosition();
    }
    public abstract void updatePosition(){ 
        //override this method in children
    }

}
相关问题