java - Java 中有 "local interface"这样的东西吗?

标签 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();
    }
}

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

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();
    }
}

Java 提示“成员接口(interface) Bar 只能在顶级类或接口(interface)中定义”。是否有一个原因?还是我遗漏了我犯的错误?

最佳答案

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

至于弱的原因,根据JLS 14.3 :

All local classes are inner classes (§8.1.3).

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

Member interfaces (§8.5) are implicitly static so they are never considered to be inner classes.

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

我猜,这是@SotiriosDelimanolis 发现 InterfaceDeclaration 不是 BlockStatement 的补充。

关于java - Java 中有 "local interface"这样的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516375/

相关文章:

java - 为什么 THREAD-1 和 THREAD-2 不交错?

java - 以设定的时间间隔在单独的进程上触发 Android Activity 方法

java - 在java中实现接口(interface)和抽象类中都存在的方法

c++ - 为什么允许泛型 lambdas 而不允许使用模板化方法的嵌套结构?

c++ - 将本地类函数指针传递给 std::list::sort

java - 两个身份列

c++ - 为自定义类和库类实现通用接口(interface)的最佳方法

Java编写库

java - 为什么即使外部类对象被销毁,内部类实例仍保留在内存中?

java - 如何在Windows上调用与Redis集成的Restful api方法?