Search code examples
javarendersubclassabstractgame-loop

How would an abstract render method work? (Java)


So say you want to have an abstract class called play, which has a render method.

public abstract class RenderPanel{

    public abstract void render();

}

And then you have another class which calls the render method using some sort of game loop.

public class Window implements Runnable{

public void run(){

    while(running){
        RenderPanel.render();
        Thread.sleep(5000);
    }
}

}

This code would not work because you cannot call an abstract class statically, and you can't instantiate the class.

So how would you go about this so that if you make a subclass of RenderPanel, the render method in the subclass will be called automatically?


Solution

  • Java keeps runtime type information (RTTI). This means that even if you hold a reference to a base class object the sub-class's method will be called(if the method is overriden by the subclass). So you don't have to do anything so as the subclass method to be called.

    public class SubRenderPanel extends RenderPanel{
       @Override
       public abstract void render()
       {
           //Do your stuff here
       }
    }
    
    public class Window implements Runnable{
        RenderPanel r = new SubRenderPanel();
        public void run(){
            while(running){
    
                r.render();
                Thread.sleep(5000);
            }
        }
    }