Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Force implementation of an implemented method

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
    }
}
like image 840
Alle Avatar asked Feb 22 '23 04:02

Alle


1 Answers

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
    }
}
like image 62
MByD Avatar answered Feb 23 '23 16:02

MByD