方法内部不允许接口

Sil*_*cea 3 java methods scjp interface

我已经学习了一些OCPJP 7认证的书籍,在内部课程章节中有一些奇怪/不完整的信息.我试图在方法中创建一个接口,但似乎你不能这样做,你只能在方法中创建类.你有什么理由不能这样做,或者它只是一个缺失的功能?

示例代码:

public class Outer {
  public void method() {
    class C {} // allowed
    interface I {} // interface not allowed here
  }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*kov 7

如果您仔细阅读Java教程,您将看到:

您不能在块内声明接口,因为接口本质上是静态的.

这意味着如果你有一个接口,就像这样:

public class MyClass {
   interface MyInterface {
       public void test();
   }
}
Run Code Online (Sandbox Code Playgroud)

你将能够做到

MyClass.MyInterface something = new MyClass.MyInterface() {
    public void test () { .. }
};
Run Code Online (Sandbox Code Playgroud)

因为MyInterface会明确的static.绑定到封闭类的实例是没有意义的,因为它只提供了一些抽象,它不必绑定到特定实例或封闭类的状态.

同样的情况也是如此,其中接口嵌套在方法中.方法内部没有任何内容(显式)static(因为非静态方法与enlosing类的特定实例相关联),因此您不能拥有本地接口.