我正在测试是否可以在 Java 接口(interface)中设置非静态、非最终字段。我很惊讶地发现,在 Eclipse 中编写程序时,如果我创建如下所示的界面,它不会提示。它甚至可以编译并运行:
public interface Interface
{
public String nonStaticField = "Not static";
}
当然,它阻止了我更改 main 方法中字段的值。但是我想知道编译器允许缺少 static 和 Final 单词的原因是否是因为它们是隐式的,或者此语法是否有任何用途。
最佳答案
来自documentation本身:
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.
所以,是的,它是隐式的,您可以不指定其中任何一个,因为接口(interface)内的字段必须是最终的和静态的。
关于java - Eclipse 编辑器允许接口(interface)中缺少 static 和 Final 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35536180/