How would an abstract render method work? (Java)

瘦欲@ 提交于 2019-12-13 02:57:51

问题


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?


回答1:


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);
        }
    }
}



回答2:


The idea is to create a new class that extends RenderPanel and use that one:

public class SubRender extends RenderPanel{
       @Override
       public abstract void render()
       {
           //Do your stuff here
       }

}

Then you want to create an instance of that SubRender and use it as the RenderPanel:

public class Window implements Runnable{

public void run(){

    while(running){
        //The subRender will act as a RenderPanel, so class specific functions will be hidden. Is just like using an java interface.
        RenderPanel r = new SubRender();
        r.render();
        Thread.sleep(5000);
    }
}

}

What you have right now is basically an abstract class serving as an interface. I would advise you to use an interface instead. Abstract classes are most commonly used to provide common behaviour to "types" of objects, in your case you would want to have "types" of renders.

However that common behaviour is missing, so I would use an Interface instead.

Study some of the Java tutorial available over the internet. This is a pretty basic java question. Search about Java interfaces, Sub classes (polymorphism).



来源:https://stackoverflow.com/questions/22366204/how-would-an-abstract-render-method-work-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!