多重继承没有多重继承,没有代码重复 [英] Multiple inheritance without multiple inheritance and without code duplication
问题描述
我有关于如何应对不允许多重继承的语言以下情形的理论问题。
I have a theoretical question concerning how to deal with the following scenario in a language which does not allow multiple inheritance.
想象一下,我有一个基类的美孚的,从中我希望创建三个子类:
Imagine I have a base class Foo and from it I am wishing to create three sub-classes:
- 类的栏的继承的富的和实现的功能A
- 类的巴兹的继承的富的并实现功能b
- 类的 Qux 的继承的富的并实现功能A和b
- Class Bar inherits Foo and implements functionality "A"
- Class Baz inherits Foo and implements functionality "B"
- Class Qux inherits Foo and implements functionalities "A" and "B"
想象一下代码来实现功能的A和b是永远不变的。有没有写A和B只有一次的代码,然后有相应的类应用(或继承)的方式呢?
Imagine that the code to implement functionalities "A" and "B" is always the same. Is there a way to write the code for "A" and "B" only once, and then have the appropriate classes apply (or "inherit") it?
推荐答案
好吧,我可以看到你在C#中实现这一目标的唯一途径/ Java是由组成。试想一下:
Well the only way I can see you achieving this in C#/Java is by composition. Consider this:
class Foo {
}
interface A {
public void a();
}
interface B {
public void b();
}
class ImplA implements A {
@Override
public void a() {
System.out.println("a");
}
}
class ImplB implements B {
@Override
public void b() {
System.out.println("b");
}
}
class Bar extends Foo {
A a = new ImplA();
public void a() {
a.a();
}
}
class Baz extends Foo {
B b = new ImplB();
public void b() {
b.b();
}
}
class Qux extends Foo {
A a = new ImplA();
B b = new ImplB();
public void b() {
b.b();
}
public void a() {
a.a();
}
}
现在 Qux
既有通过正常的继承富
的功能,而且 A
和 b
。
Now Qux
has both the functionality of Foo
via normal inheritance but also the implementations of A
and B
by composition.
这篇关于多重继承没有多重继承,没有代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!