【问题标题】:Why is calling an interface method directly from the interface (with no implementation) working?为什么直接从接口(没有实现)调用接口方法?
【发布时间】:2020-06-07 14:07:57
【问题描述】:

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

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

这是 Gdx 类的相关部分:

public class Gdx {

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

以及Input的相关部分:


public interface Input {

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

}

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

我不明白为什么,看起来好像我在调用一个没有实现的接口方法。

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

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

【问题讨论】:

  • 它在库的其他地方通过具体代码(可能是本机代码)实现,并分配给静态字段。
  • 每个后端都有一个实现这个接口的类。例如,有LwjglInputAndroidInput。如果您使用调试器并检查 Gdx.input 的值是什么类型,您就会知道正在使用什么类。

标签: java methods interface libgdx


【解决方案1】:

来自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;
}

所以你可以看到文档说这个类包含对ApplicationGraphicsAudioInputinstances的引用。但是它们是如何以及在哪里实施的?

LibGDX 知道它运行在哪种类型的设备上并相应地选择实现,例如在 Input 实现案例中,如果我们在 Android 设备上运行,我们将使用 AndroidInput 实现:
@ 987654324@

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 2021-01-14
    • 2017-08-07
    相关资源
    最近更新 更多