gpt4 book ai didi

java - 从内部类到外部接口(interface)的非静态访问的基本障碍

转载 作者:搜寻专家 更新时间:2023-10-30 20:01:36 24 4
gpt4 key购买 nike

例子:

interface Outer {
default String get() {
return "hi";
}
class Inner {
String got() {
return get();
}
}
}

这会产生错误

java: non-static method get() cannot be referenced from a static context.

内部接口(interface)/类总是静态的;与外部类不同,除非声明为静态,否则它是非静态的。

这就是今天和即将到来的 java 8 中的情况。外部类和外部接口(interface)之间的这种差异是否有根本原因?

更新:阅读@Radiodef 的评论后,我将内部接口(interface)更改为内部类。外部类不能包含非静态内部接口(interface),因此该示例令人困惑。无论如何,内部类确实是我想要的。

更新:供引用。这是完全合法的:

class Outer {
String get() {
return "hei";
}
class Inner {
String got() {
return get();
}
}
}

最佳答案

也许我误解了你的问题,但你的代码片段完全等同于

interface Outer {
public default String get() {
return "hi";
}
public static class Inner {
String got() {
return get();
}
}
}

作为the JLS Chapter 9.5 (Java 8)

A member type declaration in an interface is implicitly public and static. It is permitted to redundantly specify either or both of these modifiers.

如果你这样做了

Inner innerInstance = new Outer.Inner();
innerInstance.got();

get() 会在什么情况下被调用?这里不涉及Outer类型的对象。

Is there a fundamental reason for this difference between outer classes and outer interfaces?

这不是问题。 你的类(class)代码是inner classes的例子,即。非 static 嵌套类。 接口(interface)代码是一个static嵌套类的例子。您正在比较两种不同的事物。

在封闭类中具有 static 嵌套类的等效示例是

class Outer {
String get() {
return "hei";
}

public static class Inner {
String got() {
return get(); // won't compile
}
}
}

再次,get() 工作没有意义,因为没有相应的(封闭的)实例来调用它。


如题,如@Radiodef说起来,就是

why must the class be implicitly static beyond that this is the existing spec?

那么我的答案如下:

接口(interface),顾名思义,就是

A point at which independent systems or diverse groups interact

接口(interface)没有状态,也没有行为。它只是描述行为。接口(interface)成员是隐式的 static 因为接口(interface)没有状态。

关于java - 从内部类到外部接口(interface)的非静态访问的基本障碍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418802/

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