gpt4 book ai didi

Java Docs 说接口(interface)不能有字段。为什么?

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:18 25 4
gpt4 key购买 nike

我正在阅读 this并且它清楚地指出 类和接口(interface)之间的一个显着区别是类可以有字段而接口(interface)不能。这怎么可能因为 Java 文档还说 接口(interface)中的所有字段都是公共(public)的,静态的和最终的

最佳答案

How could this be possible because Java Docs also says all fields in interface are public, static and final.

来自 Java Language Specification. Chapter 9. Interfaces. 9.3. Field (Constant) Declarations (强调我的):

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for ConstantModifier.

这意味着接口(interface)中的每个字段都将被视为一个public常量字段。如果您添加 publicstaticfinal 或这些修饰符中的一些或不添加它们,编译器将为您添加它们。这就是隐式的意思。

所以,有了这个:

interface Foo {
String bar = "Hello World";
}

类似于有

interface Foo {
public String bar = "Hello World";
}

类似于

interface Foo {
static bar = "Hello World";
}

这三个接口(interface)将编译为相同的字节码。

此外,请确保您在接口(interface)中的字段声明遵循子注释。这意味着,您无法缩小界面中某个字段的可见性。这是非法的:

interface Foo {
//compiler error!
private String bar = "Hello World";
}

因为 bar 不会是 public 并且它违背了接口(interface)中字段的标准定义。

关于Java Docs 说接口(interface)不能有字段。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23760759/

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