java - 为什么直接从接口(interface)调用接口(interface)方法(没有实现)可以工作?

标签 java methods interface libgdx

这是来自 LibGDX 框架,我正在调用该方法

Gdx.input.isKeyPressed(Input.Keys.LEFT);

这是 Gdx 类的相关部分:

public class Gdx {

    //..
    public static Input input;
    //..
}

以及输入的相关部分:


public interface Input {

    //..
    public class Keys { //..
    }
    //..
    public boolean isKeyPressed (int key);
    //..

}

最糟糕的是它还能工作!如果我按向左箭头,则返回 true。

我不明白为什么,看起来好像我在调用接口(interface)方法而没有实现。

我将保留两个类的源代码的链接:

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/Gdx.java

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/Input.java

最佳答案

来自source code :

/** Environment class holding references to the {@link Application}, {@link Graphics}, {@link Audio}, {@link Files} and
 * {@link Input} instances. The references are held in public static fields which allows static access to all sub systems. Do not
 * use Graphics in a thread that is not the rendering thread.
 * <p>
 * This is normally a design faux pas but in this case is better than the alternatives.
 * @author mzechner */
public class Gdx {
    public static Application app;
    public static Graphics graphics;
    public static Audio audio;
    public static Input input;
    public static Files files;
    public static Net net;

    public static GL20 gl;
    public static GL20 gl20;
    public static GL30 gl30;
}

所以你可以看到文档说这个类持有对ApplicationGraphicsAudio实例的引用和输入。但它们是如何以及在哪里实现的呢?

LibGDX知道它正在运行哪种类型的设备并选择相应地实现,例如在Input中实现案例如果我们在 Android 设备上运行,我们会选择 AndroidInput实现:
enter image description here

所有这些都是我们在后台自动完成的,因此我们更专注于制作出色的游戏/应用程序。
所以当我们使用时确实如此:

Gdx.input.isKeyPressed(Input.Keys.LEFT);

我们正在为我们的设备使用正确的Input实现,而不是从接口(interface)本身调用该方法。

关于java - 为什么直接从接口(interface)调用接口(interface)方法(没有实现)可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60367543/

相关文章:

groovy - 如何使用 groovy mixin 添加静态方法

安卓假触摸界面

java - 正则表达式:匹配逗号后不跟数字

java - 未指定 maxSize 时,Google Guava Cache 逐出 SIZE 条目

java - 使用非静态方法而不将其引用到对象?

java - 如何从不同的类和包访问对象?

java - 为什么任何类型都可以EXTENDS接口(interface)?

Java - 将对象的 ArrayList 传递给使用对象实现的接口(interface)的 ArrayList 的函数

java - 访问树集中的元素

JavaFX:WindowEvent.WINDOW_HIDDEN