Java中是否有“本地接口”之类的东西?

Mar*_* A. 4 java interface local-class

Java 允许我定义本地抽象类,就像在这个例子中一样:

public class Foo {

    public void foo() {
        abstract class Bar {          // Bar is a local class in foo() ...
            abstract void bar();
        }

        new Bar() {                   // ... and can be anonymously instantiated
            void bar() {
                System.out.println("Bar!");
            }
        }.bar();
    }
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当我尝试定义“本地接口”而不是本地类时,如下所示:

public class Foo {

    public void foo() {
        interface Bar {           // Bar was supposed to be a local interface...
            void bar();
        }

        new Bar() {               // ... to be anonymously instantiated
            void bar() {
                System.out.println("Bar!");
            }
        }.bar();
    }
}
Run Code Online (Sandbox Code Playgroud)

Java 抱怨“成员接口 Bar 只能在顶级类或接口中定义”。是否有一个原因?还是我错过了我犯的错误?

Sot*_*lis 5

Java 语言规范并没有告诉您为什么按照原来的方式设计它,但它确实描述了什么是允许的,什么是不允许的。

方法体具有以下形式

MethodBody:
    Block 
    ;
Run Code Online (Sandbox Code Playgroud)

这里Block

Block:
    { BlockStatementsopt }

BlockStatements:
    BlockStatement
    BlockStatements BlockStatement

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement
Run Code Online (Sandbox Code Playgroud)

所以类声明是允许的,但接口不是。


我们可以争辩说,从调用者的角度来看,拥有本地接口并不是很有用。它没有任何用途。接口旨在描述行为,但由于接口是本地的,没有调用者可以使用它。您也可以在类中定义和实现行为。


Rad*_*def 5

JLS 中根本没有对它的定义。它只是不存在。

至于一个弱的原因,根据JLS 14.3

所有本地类都是内部类(第 8.1.3 节)。

接口不能是内部的(JLS 8.1.3):

成员接口(第 8.5 节)是隐式静态的,因此它们永远不会被视为内部类。

所以我们不能有本地接口。

这是,我想,除了@SotiriosDelimanolis 发现 InterfaceDeclaration 不是 BlockStatement 之外。