且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中实现多重继承

更新时间:2022-10-14 23:17:19

要回顾一下,您必须:

class A
{
    public void foo() {}
}

class B extends A
{
    public specificAMethod() {}
}

class C extends A
{
    public specificCMethod() {}
}

以上类位于您无法访问或修改的库中. 您想获得B和C在第三类D中的行为,就好像可以写:

class D extends B, C
{
}

对吗?

使用B和C而不是继承该怎么办?您真的需要继承吗?您要调用私有的B和C方法吗?

class D
{

private B b;
private C c;
}

I'm working with a certain API library in Java. It has a base class A, as well as B and C which both extend A. B & C provide similar but distinct functionality, all three classes are in the library.

public abstract class A
{
    virtual foo();
}

public class B extends A {}
public class C extends A {}

How do I get elements of A, B, and C in my class? If I use interfaces to implement the classes, there is a lot of duplicate code, and inner classes will not allow me to override existing methods so that the calling interfaces of A, B, and C are preserved.

How do I implement multiple inheritence in Java?

EDIT: Thanks for edit George, its more clear now, forgot to mention one critical requirement: my classes must have A as a base so that they can be managed by platform API.

To recap, you have:

class A
{
    public void foo() {}
}

class B extends A
{
    public specificAMethod() {}
}

class C extends A
{
    public specificCMethod() {}
}

The above classes are in a library that you can't access or modify. You want to get the behaviour of both B and C in a third class D, as if it were possible to write:

class D extends B, C
{
}

Right?

What about using B and C instead of inheriting? Do you really need inheritance? You want to call private B and C methods?

class D
{

private B b;
private C c;
}