gpt4 book ai didi

java - 接口(interface)是否解决了 "deadly diamond of death"问题?

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:31 25 4
gpt4 key购买 nike

做接口(interface)解决deadly diamond of death问题?

我不这么认为,例如:

// A class implementing two interfaces Interface1 and Interface2.
// Interface1 has int x=10 and Interface2 has int x = 20

public class MultipleInterface implements Interface1, Interface2{

public void getX(){
System.out.println(x);
}
}

这里我们得到一个不明确的 x

虽然接口(interface)是解决方法歧义的好方法,但我猜它们在变量的情况下会失败吗?

我说的对吗?如果我遗漏了什么,请启发我。

最佳答案

当一个类从父接口(interface)继承两个变量时,Java 坚持对相关变量名的任何使用都是完全限定的。这解决了问题。查看Java Language Specification Section 8.3 :

It is possible for a class to inherit more than one field with the same name. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.

类似的声明适用于接口(interface) ( JLS §9.3 )。

the answer by Óscar López中的示例代码很棒。这是另一个例子:

class Base {
int x = 10;
}

interface Interface {
int x = 20;
}

class SingleInheritance implements Interface {
int y = 2 * x; // ok
}

class MultipleInheritance extends Base implements Interface {
int y = 2 * x; // compile-time error
int z = 2 * Interface.x; // ok
}

void aMethod(MultipleInheritance arg) {
System.out.println("arg.x = " + arg.x); // compile-time error
System.out.println("x = " + Interface.x); // ok
}

编辑

Java 8 为方法引入了一种有限形式的多重继承,因为接口(interface)现在可以声明 default methods子接口(interface)和实现类可以继承。由于一个类可以实现多个接口(interface),这可能会导致歧义,因为具有相同签名的不同默认方法可以从多个接口(interface)继承。1 Java 使用优先级方案来处理这个问题,以指定哪个默认方法实际上是遗传。当优先级方案未能产生单个获胜者时,它需要显式覆盖继承的默认方法。

请注意,在任何情况下,Java 都不会存在菱形问题,它是多重继承可能带来的问题的一个非常具体的子类。2“菱形”部分指的是类的形状解决问题所需的继承图。在 C++ 中,如果类 A 继承自两个类 B 和 C,每个类都继承自一个公共(public)基类 D,就会出现菱形继承(钻石问题)。在这种情况下,D 的任何公共(public)成员最终会在 A 中出现两次——一次是通过B 和一次通过 C。此外,无论何时构造或销毁 A 的实例,D 的构造函数或析构函数最终都会被调用两次(通常会带来灾难性的后果,因此名称中的“死亡”部分)。 C++ 通过提供虚拟继承 解决了这些问题。 (有关详细信息,请参阅讨论 here。)

1 请注意“不同”一词的使用。如果相同默认方法是通过两个父接口(interface)继承的,这两个父接口(interface)又扩展了定义默认方法的公共(public)基接口(interface),则没有问题;默认方法只是继承。

2 其他多重继承问题——例如 Java 中可能出现的接口(interface)字段、静态方法和默认方法的歧义——在技术上与菱形继承(钻石问题)无关(实际上, Deadly Diamond of Death 问题)。然而,关于该主题的大部分文献(以及该答案的早期版本)最终将所有多重继承问题归为“死亡钻石”这一标题。我想这个名字太酷了,只能在技术上合适的时候使用。

关于java - 接口(interface)是否解决了 "deadly diamond of death"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com