特别是,如果接口(interface)不一致,编译/运行时幕后发生的事情会产生错误?
接口(interface)示例:
public interface Interface1 {
int NUM = 0;
}
public interface Interface2 {
int NUM = 1;
}
这有一个编译器错误:
public class Test implements Interface1, Interface2 {
public static void main(String[] args) {
System.out.println(NUM);
}
}
运行得很好:
public class Test implements Interface1, Interface2 {
public static void main(String[] args) {
System.out.println("anything");
}
}
当java遇到NUM
时,它会从接口(interface)中查找定义。它无法同时检查两者,那么为什么它不直接使用 Interface1
中的定义(首先实现)呢?它的设计目的是为了检查所有接口(interface)的一致性吗?
最佳答案
本质上,你在这里得到的是 diamond problem - Interface1
有一个字段,Interface2
有一个字段。它们都在其实现类中使用,但哪一个“获胜”是未定义的。如果 Interface1.NUM
为 100 而 Interface2.NUM
为 1000 会怎样?那么行为会是什么?如果行为不一致怎么办 - 有时在运行期间它变成 100,有时它变成 1000?
哪个 NUM
被定义为“第一个”是不明确的。没有具体说明哪个接口(interface)实际上被接受为序列中的“第一个”接口(interface)。 Java 对实现的了解不够多,无法信任一种实现而不是另一种实现,因此它放弃了——这两种实现都太模糊,无法让运行时做出判断调用。
关于java - Java如何判断接口(interface)是否不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766880/