钻石问题与Groovy特征 [英] Diamond Issue with Groovy traits

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

问题描述

在很多关于Groovy Traits的博客中都提到它将解决钻石问题。但是这个概念对我来说并不清楚,特质是如何解决钻石问题的。

请任何人解释一下。

解决方案

钻石问题是问题,当你有多个继承和两个或更多的超类定义一个或多个具有相同签名的功能。

使用groovy特征,行为是明确的。

 特质A {
String name(){A}

特性B {
字符串名称(){B}
}
class C implements A,B {}
class D implements B, A {}

声明新的C()。name()==B
声明新的D()。name()==A

也可以选择你想要的:

  class E implements A,B {
String name(){A.super.name()+ B.super.name()}
}

assert new E()。name()==AB


In many blog about Groovy Traits it's mentioned that it will solve the Diamond Problem. But the concept is not clear to me that how traits will solve the Diamond Problem.

Can any one explain please.

解决方案

The diamond problem is a problem when you have multiple inheritance and two or more super classes define one or more functions with the same signature.

With groovy traits, the behaviour is well-defined. By default, the last implementation is chosen.

trait A {
    String name() { "A" }
}
trait B {
    String name() { "B" }
}
class C implements A,B { }
class D implements B,A { }

assert new C().name() == "B"
assert new D().name() == "A"

It is also possible to choose the one you want:

class E implements A,B {
    String name() { A.super.name() + B.super.name() }
}

assert new E().name() == "AB"

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

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