How could this be possible because Java Docs also says all fields in interface are public, static and final.
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.
这意味着界面中的每个字段都将被视为公共常量字段.如果你添加public,static和final或其中一些修饰符,或者没有添加它们,编译器会为你添加它们.这是含蓄的含义.
所以,有这个:
interface Foo {
String bar = "Hello World";
}
类似于
interface Foo {
public String bar = "Hello World";
}
这类似于
interface Foo {
static bar = "Hello World";
}
这三个接口将编译为相同的字节码.
另外,请确保接口中的字段声明遵循子注释.这意味着,您无法缩小界面中字段的可见性.这是非法的:
interface Foo {
//compiler error!
private String bar = "Hello World";
}
因为bar不是公共的,它违反了接口中字段的标准定义.