钻石问题 [英] Diamond Problem

查看:534
本文介绍了钻石问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于钻石问题的维基百科:

Wikipedia on the diamond problem:

......当两个B类和C类从A继承而D类继承时,钻石问题就出现了歧义如果D中的方法调用A中定义的方法(并且不覆盖该方法),并且B和C以不同的方式覆盖该方法,那么它继承的是哪个类:B还是C?

"... the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?"

所以钻石看起来像这样:

So the diamond looks like this:

  A
 / \
B   C
 \ /
  D

我的问题是,如果没有这样的A类会发生什么,但B和C再次声明相同的方法,比如说foo()。这不是同一个问题吗?为什么它被称为钻石问题?

My question is, what happens if there is no such class A, but again B and C declare the same method, say foo(). Isn't this the same problem? Why is it then called diamond problem?

示例:

class B {
    public void foo() {...}
}

class C {
    public void foo() {...}
}

class D extends B, C {
}

new D().foo();


推荐答案

它不是同一个问题。

在原始问题中,可以从A调用overriden方法。在你的问题中,情况并非如此,因为它不存在。

In the original problem, the overriden method can be called from A. In your problem this can't be the case because it does not exist.

在钻石问题中,如果A类调用方法Foo,则会发生冲突。通常这没问题。但是在D类中你永远不知道需要调用哪个Foo实例:

In the diamond problem, the clash happens if class A calls the method Foo. Normally this is no problem. But in class D you can never know which instance of Foo needs to be called:

         +--------+
         |   A    |
         | Foo    |
         | Bar    |
         +--------+
            /  \
           /    \
          /      \
+--------+        +--------+
|   B    |        |   C    |
| Foo    |        | Foo    |
+--------+        +--------+
          \      /
           \    /
            \  /
         +--------+
         |   D    |
         |        |
         +--------+

在您的问题中,没有可以调用该方法的共同祖先。在D级,你可以选择两种Foo,但至少你知道有两种。你可以在两者之间做出选择。

In your problem, there is no common ancestor that can call the method. On class D there are two flavors of Foo you can chose from, but at least you know that there are two. And you can make a choice between the two.

+--------+        +--------+
|   B    |        |   C    |
| Foo    |        | Foo    |
+--------+        +--------+
          \      /
           \    /
            \  /
         +--------+
         |   D    |
         |        |
         +--------+

但是,一如既往,你做不需要多重继承。您可以使用aggegration和接口来解决所有这些问题。

But, as always, you do not need multiple inheritance. You can use aggegration and interfaces to solve all these problems.

这篇关于钻石问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆