Java - Force implementation of an implemented meth

2019-06-25 08:48发布

问题:

I have three classes which I have a problem with. They are named: GameScene, StageScene, StageOne. My problem is that I want to implement initialize in StageScene, but still force StageOne to implement it, so that whenever someone uses a StageOne object (stageOne.initialize()), initialize would be run for both StageScene and StageOne. Anyone know how this could be done?

public abstract class GameScene 
{
    public abstract void initialize();
}

public abstract class StageScene extends GameScene
{
    public abstract void initialize()
    {
        //Some code
    }
}
public class StageOne extends StageScene
{
    public void initialize()
    {
        //Some code
    }
}

回答1:

you can do it with a wrapper:

public abstract class StageScene extends GameScene
{
    final public void initialize()
    {
        //your initialization
        subInitialize();
    }

    protected abstract void subInitialize();
}

And in the child class:

public class StageOne extends StageScene
{
    public void subInitialize()
    {
        //Some code
    }
}


回答2:

You could break it into two separate methods

public abstract class GameScene 
{
    public abstract void initializeScene();
    public abstract void initializeStage();
}

public abstract class StageScene extends GameScene
{
    public void initializeScene()
    {
        //Some code
    }
}
public class StageOne extends StageScene
{
    public void initializeStage()
    {
        //Some code
    }
}