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

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

问题描述

假设你想要一个名为 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.

那么你会怎么做,如果你创建一个RenderPanel的子类,子类中的render方法会被自动调用?

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

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

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