gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:11:01 24 4
gpt4 key购买 nike

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/

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