我有个问题想问你?众所周知,Java中的接口(interface)字段默认是public、static和final。扩展接口(interface)怎么样? 例如,如果我们有一些其中定义了字段的接口(interface),并且我们创建了另一个用字段扩展接口(interface)的接口(interface),那么我们不应该能够继承字段,因为它们实际上是静态的,也是最终的。但我们可以!那么你能向我解释一下为什么吗?
interface interfaceWithFields{
String name = "Matthew";}
interface interfaceWithoutFields extends interfaceWithFields{}
当我们调用标准输出方法时,它将返回 Matthew:
System.out.println(interfaceWithoutFields.name); //no problem at all
提前感谢您的回复。现在已经很晚了,我可能混淆了一些东西。
最佳答案
这是正常的。子类和子接口(interface)通常从其父类(super class)型继承静态成员。*
9.2 :
The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields, classes, and interfaces that it hides; abstract or default methods that it overrides (§9.4.1); and
static
methods.
那里的措辞有点,嗯,罗嗦,但它说接口(interface)从 super 接口(interface)继承静态字段,除非它们没有被隐藏。 (隐藏是当您声明具有相同名称的变量时。)
实际上,编译器只会将 interfaceWithoutFields.name
替换为 interfaceWithFields.name
。仅存在一个静态变量name
。
*(奇怪的是,静态方法不是从 super 接口(interface)继承的。)
关于java - 使用定义的字段扩展接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36510927/