gpt4 book ai didi

java - 访问静态成员类

转载 作者:行者123 更新时间:2023-11-29 03:05:23 25 4
gpt4 key购买 nike

我了解到,要访问静态成员类,语法是OuterClass.NestedStaticClass

对于下面给定的接口(interface)Input

interface Input{

static class KeyEvent{
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 0;
public int type;
public int keyCode;
public int keyChar;
}

static class TouchEvent{
public static final int TOUCH_DOWN = 0;
public static final int TOUCH_UP =0;
public static final int TOUCH_DRAGGED = 2;
public int type;
public int x, y;
public int pointer;
}

public boolean isKeyPressed(int keyCode);
.....
public List<KeyEvent> getKeyEvents();
public List<TouchEvent> getTouchEvents();
}

下面是Keyboard的实现,

class Keyboard implements Input{

....

@Override
public List<TouchEvent> getTouchEvents() {
TouchEvent obj1 = new TouchEvent();
TouchEvent obj2 = new TouchEvent();
List<TouchEvent> list = new ArrayList<TouchEvent>();
list.add(obj1);
list.add(obj2);
return list;
}

}

在此实现 Keyboard 中,我不需要为以下代码行使用 Input.TouchEvent

TouchEvent obj1 = new TouchEvent();
TouchEvent obj2 = new TouchEvent();
List<TouchEvent> list = new ArrayList<TouchEvent>();

但是对于下面的实现,我不得不使用Input.TouchEvent

public class NestedClassInInterface {
public static void main(String[] args) {
Input.TouchEvent t = new Input.TouchEvent();
}
}

我怎么理解这个?

最佳答案

来自 Java 语言规范,concerning members of an interface type

The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).

关于 scope of a declaration

The scope of a declaration of a member m declared in or inherited by a class type C (§8.1.6) is the entire body of C, including any nested type declarations.

concerning class members

The members of a class type are all of the following:

  • [..]
  • Members inherited from any direct superinterfaces (§8.1.5)

因此,类型TouchEvent 是在类型Input 中声明的。它是 Input 的成员。 Keyboard 实现了 Input,因此继承了它的成员。 TouchEvent 因此在 Keyboard 的主体范围内。因此,您不需要用它的封闭类型来限定它的使用。

关于java - 访问静态成员类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470455/

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