我研究了一些 OCPJP 7 认证的书籍,在内部类章节中有一些奇怪/不完整的信息。我试过在一个方法中创建一个接口(interface),但似乎你不能那样做,你只能在一个方法中创建类。您有什么理由不能这样做,或者这只是一个缺失的功能?
示例代码:
public class Outer {
public void method() {
class C {} // allowed
interface I {} // interface not allowed here
}
}
最佳答案
如果您仔细阅读Java Tutorials ,你会看到:
You cannot declare an interface inside a block, because interfaces are inherently static.
这意味着如果你有一个像这样的界面:
public class MyClass {
interface MyInterface {
public void test();
}
}
你将能够做到
MyClass.MyInterface something = new MyClass.MyInterface() {
public void test () { .. }
};
因为MyInterface
将显式static
。绑定(bind)到封闭类的实例没有意义,因为它只是提供了一些抽象,不必绑定(bind)到特定实例或封闭类的状态。
同样的情况也适用于接口(interface)嵌套在方法中的情况。方法内部的任何内容都不能(明确地)static
(因为非静态方法绑定(bind)到封闭类的特定实例),因此您不能拥有本地接口(interface)。
关于java - 方法内部不允许接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180446/