抽象渲染方法将如何工作? (Java) [英] How would an abstract render method work? (Java)

查看:144
本文介绍了抽象渲染方法将如何工作? (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以说您想拥有一个名为play的抽象类,它具有一个render方法。

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?

推荐答案

Java会保留运行时类型信息(RTTI)。这意味着即使您拥有对基类对象的引用,也会调用子类的方法(如果该方法被子类覆盖)。因此,您无需执行任何操作即可调用子类方法。

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

这篇关于抽象渲染方法将如何工作? (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆