简体   繁体   English

当前两个已经处于基-子类关系中时,如何继承第三个类中的两个类?

[英]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.

相关问题 它们与第三个类相关联的两个类之间有什么关系? - What is the relationship between two classes they are tied to a Third class? 我如何制作可以同时运行这两个课程的第三堂课? - How can I make a third class that could run these two classes? 如何在UML类图中表示两个类之间的可互换关系 - How to represent a interchangeable relationship between two classes in UML class Diagram Java:一个类可以同时从两个超类继承吗? - Java: Can a class inherit from two super classes at the same time? 如何从两个类继承 - How to inherit from two classes Java:当其他类已经扩展基类时,如何扩展基类? - Java: How to extend a base class when other classes already extend the base? 如何允许基本自动配置类? 当我有两个扩展它时,只有第一个被调用 - How allow base auto configuration class? When I have two that extend it, only the first one gets called 使用硒实现两类到第三类功能的体系结构 - Architecture for implementing functionalities of two classes to a third class using selenium Java:具有主要方法的两个类访问相同的第三类 - Java: Two classes with main methods accessing the same third class Java:如何在第三类中创建两个不同类的实例,并通过构造函数相互传递引用 - Java: how to create instances of two different classes in a third class and pass references to each other through the constructors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM