Java Docs说接口不能有字段.为什么?

Fre*_*her 4 java interface

我正在读这篇文章,它清楚地表明,One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot.如果可能,这可能是因为Java Docs也说all fields in interface are public,static and final.

Lui*_*oza 5

这怎么可能,因为Java Docs还说接口中的所有字段都是public,staticfinal.

来自Java语言规范.第9章接口.9.3.Field(Constant)声明(强调我的):

在接口的身体的每一个字段声明是含蓄 public,staticfinal.允许为这些字段冗余地指定任何或所有这些修饰符.

如果两个或多个(不同的)字段修饰符出现在字段声明中,则通常(尽管不是必需的)它们按照与上面生产中显示的顺序一致的顺序出现ConstantModifier.

这意味着界面中的每个字段都将被视为public常量字段.如果添加public,staticfinal或某些改性剂或没有人的,编译器会增加你的问题.这是含蓄的含义.

所以,有这个:

interface Foo {
    String bar = "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

类似于

interface Foo {
    public String bar = "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

这类似于

interface Foo {
    static bar = "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

这三个接口将编译为相同的字节码.

另外,请确保接口中的字段声明遵循子注释.这意味着,您无法缩小界面中字段的可见性.这是非法的:

interface Foo {
    //compiler error!
    private String bar = "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

因为它bar不会public并且它违反了接口中字段的标准定义.