访问静态成员 class

Accessing static member class

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

对于下面给出的接口 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();
    }
}

我怎么理解这个?

引自doc:

The scope (§6.3) of a member (§8.2) is the entire body of the declaration of the class to which the member belongs. Field, method, member class, member interface, and constructor declarations may include the access modifiers (§6.6) public, protected, or private. The members of a class include both declared and inherited members (§8.2)

所以这意味着 class Keyboard 在其范围内也有 Input 的成员,并且可以直接访问它们。

由于您的 class Keyboard 实现了接口 Input,这意味着 Keyboard Input。并且可以直接访问static nested class而不用引用外部接口。默认情况下,所有接口字段也是静态的,但实现 class 可以直接访问它们。

但是当您尝试在 NestedClassInInterface(不是 Input)中访问它时,它需要引用外部 class/interface,在这种情况下是 Input。您可以尝试从 Keyboard 的声明中删除 implements Input,然后您就会明白我的意思了。

来自 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 的主体范围内。因此,您不需要用它的封闭类型来限定它的使用。