Can I increase the specification of a variable in a class extending another class in java?

I am developing a game in which I use a handler object to handle all rendering and ticking operations. Each scenecorresponds to a different object handler. Each of my handlers has a set of methods specific to this type of handler. For example, only a level handler has methods addPlayerand addEnemy.

I want to define a generic class sceneas follows:

public class Scene {
    protected Handler handler;

    public Scene(Handler handler){
        this.handler = handler;
    }

    public void render(Graphics g){
        handler.render(g);
    }
}

I would like to define a subclass of my scene, which will be a scene object specific to when a player plays a game, called levelScene:

public class LevelScene extends Scene {
    protected LevelHandler; //<- This doesn't work.
}

, LevelHandler, levelScene, scene . , - , levelScene - LevelHandler, , handler. ?

+4
1

generics. Scene , , LevelScene , LevelHandler.

public class Scene<HandlerType extends Handler> {
    protected HandlerType handler;

    public Scene(HandlerType handler){
        this.handler = handler;
    }

    public void render(Graphics g){
        handler.render(g);
    }
}

public class LevelScene extends Scene<LevelHandler> {
    @Override
    public void render(Graphics g) {
        super(g);
        handler.doLevelOnlyThing();
    }
}
+5

Source: https://habr.com/ru/post/1614981/


All Articles