[英]How to inherit two classes in a third class when the first two are in base-child class relationship already?
Say I want to inherit Class A and Class B to Class C, (here B extends A as well). 假设我想将A类和B类继承到C类(这里B也扩展了A类)。 I am very well aware that though I can never do it directly in Java, but by using Mixin inheritance (Link: http://csis.pace.edu/~bergin/patterns/multipleinheritance.html ) , that is use of one interface and other one as base class and internally using delegation I can do it, when A & B are unrelated class.
我非常清楚,尽管我永远无法直接在Java中做到这一点,但是通过使用Mixin继承(链接: http : //csis.pace.edu/~bergin/patterns/multipleinheritance.html) ,即使用了一个接口当A和B是不相关的类时,我可以做另一类作为基类并在内部使用委托。
How do I do the same when A & B have parent child them selves, and I need to inherit both of them in C? 当A和B都有自己的父母子女并且我需要在C中继承它们时,我该怎么做?
Just for your info, I am trying to do the same to achieve immutability in classes A & B. 仅为您提供信息,我正在尝试这样做以实现A和B类的不变性。
If your class B
already extends class A
, then having class C
extend class B
would already do the trick. 如果您的
class B
已经扩展了class A
,那么让class C
class B
扩展class B
就可以解决问题。 by extending class B
you also get all functionality from class A
that has not been specifically overridden in class B
通过扩展
class B
你也可以得到所有的功能class A
,至今尚未得到明确覆盖class B
Presumably you'd end up with: 大概您将得到:
class A
{
public string hello()
{
return "Hello, World!";
}
}
class B extends A
{
}
class C extends B
{
}
C foo = new C();
foo->hello(); // "Hello World!" because it is defined in A
为什么不将A类作为抽象类,然后将其扩展到B和C中呢?让您的通用方法作为A抽象体(或可以定义)位于A中,然后可以在具体类中覆盖它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.