gpt4 book ai didi

java - 外国语法 - 需要帮助理解

转载 作者:行者123 更新时间:2023-12-02 07:16:37 28 4
gpt4 key购买 nike

我已经编程几年了,所以我并不是真正的新手 - 但我刚刚开始学习 Java(从 C++)。在学习一个库并查看它的示例时(jMonkeyEngine3,如果你必须知道的话),我遇到了外来语法,我似乎找不到任何文档。

这是代码(所有代码都在类的范围内):

/** Custom Keybinding: Map named actions to inputs. */
private void initKeys() {
// You can map one or several inputs to one named action
inputManager.addMapping("Pause", new KeyTrigger(KeyInput.KEY_P));
inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_J));
inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_K));
inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE),
new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
// Add the names to the action listener.
inputManager.addListener(actionListener, new String[]{"Pause"});
inputManager.addListener(analogListener, new String[]{"Left", "Right", "Rotate"});

}

private ActionListener actionListener = new ActionListener() {
public void onAction(String name, boolean keyPressed, float tpf) {
if (name.equals("Pause") && !keyPressed) {
isRunning = !isRunning;
}
}
};

我猜测定义部分 (15) 使用类内的默认构造函数创建一个具有名为 actionListener 的私有(private)范围的 ActionListener 对象 - 然后重写/实现其本身的 onAction 方法。那么在它的实现(11)中它只是引用这个创建的对象?这是正确的吗?

非常感谢您的澄清。

最佳答案

I'm guessing that the defining piece (15) creates an object of ActionListener

该语法就是所谓的 anonymous inner class 。在 JDK 8 出现之前,它已经是最接近 Java 中的闭包或 lambda 表达式的了。您基本上是在动态创建一个新类。它实际上与您所说的一样:

private ActionListener actionListener = new MyActionListener();

class MyActionListener implements ActionListener {
public void onAction(String name, boolean keyPressed, float tpf) {
if (name.equals("Pause") && !keyPressed) {
isRunning = !isRunning;
}
}
}

另一种方式只是使用更少的行。

with a private scope

这并不完全意味着该对象是私有(private)的。私有(private)只是保存对象引用的字段的可见性。对象本身可以传递到任何地方,就像任何对象一样。

named actionListener

这是保存对所创建的 ActionListener 的引用的字段的名称。

using the default constructor inside the class

实际上,ActionListener 是一个接口(interface),因此没有构造函数。即使匿名内部类从技术上讲也没有默认构造函数。相反,它有一个 "anonymous constructor" .

关于java - 外国语法 - 需要帮助理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14868776/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com