Java中如何实现多重继承

发布于 2024-09-27 07:25:41 字数 479 浏览 2 评论 0原文

我正在使用 Java 中的某个 API 库。它有一个基类 A,以及扩展 A 的 B 和 C。 C 提供相似但不同的功能,所有三个类都在库中。

public abstract class A
{
    virtual foo();
}

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

如何在我的类中获取 ABC 元素?如果我使用接口来实现类,就会有很多重复的代码,并且内部类不允许我重写现有的方法,这样 AB 的调用接口> 和 C 被保留。

Java中如何实现多重继承?

编辑: 感谢编辑 George,现在更清楚了,忘记提及一个关键要求:我的类必须以 A 作为基础,以便可以通过平台 API 进行管理。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浮萍、无处依 2024-10-04 07:25:41

回顾一下,您拥有:

class A
{
    public void foo() {}
}

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

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

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

class D extends B, C
{
}

对吗?

使用 B 和 C 而不是继承怎么样?真的需要继承吗?你想调用私有的B和C方法吗?

class D
{

private B b;
private C c;
}

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;
}
花之痕靓丽 2024-10-04 07:25:41

如果您采用“更喜欢组合而不是继承”的一般方法,您可能会发现一个或两个类实际上不应该被“继承”。在这两种情况下,类是否具有严格的“is-a”关系?如果你能大声说出“Has-a”并且听起来并不愚蠢,那么你可能需要作曲。

例如,如果您正在实现一副纸牌,黑桃 3 是 - 3 并且它是 - 黑桃,但您也可以将其视为它有 - 3 并且它有 - 花色(黑桃)。既然你可以这样想,你可能应该更喜欢 has-a 解释和 use 组合。

尝试远离继承树超过几个对象深度 - 如果您想要使用多重继承,请尝试解决它。这是 Java 强制你通过不提供某个功能来设计代码更具可读性的情况之一(但不可否认的是,当你真正需要它时,它不存在,这可能会造成伤害!某种程度的 mixin 会是好的)。

If you take the general approach of "Prefer Composition over Inheritance", you may find out that one or both of the classes shouldn't be actually "Inherited" anyway. In both cases, do the classes have a strict "is-a" relationship? If you can say "Has-a" out loud and it doesn't sound stupid, you probably want composition.

For instance, if you are implementing a deck of cards, the 3 of spades is-a 3 and it is-a spade, but you can also think of it as it has-a 3 and it has-a suit (spade). Since you can think of it that way, you should probably prefer the has-a interpretation and use composition.

Try to stay away from inheritance trees more than a few objects deep--and if you ever feel the desire to use multiple inheritance, try to work around it. This is one of the cases where Java kind of forces you to design your code to be a little more readable by not supplying a feature (but admittedly when you really want it, it's not there and that can hurt! Some level of mixin would be nice).

儭儭莪哋寶赑 2024-10-04 07:25:41

听起来你想扩展 A - 称之为 D - 覆盖它的 foo(),然后有新的子类 E 和 foo() 。 F 扩展了 D 并添加了自己的功能。

您可能会考虑提取通用接口并重用它们。一个具有重构功能的优秀 IDE 将使这一切变得容易。

Sounds like you want to extend A - call it D - override its foo(), and then have new subclasses E & F that extend D and add their own functionality.

You might think about extracting common interfaces and reusing those. A good IDE with refactoring capability will make it easy to do.

无远思近则忧 2024-10-04 07:25:41

在 Java 中,多重类继承是不可能的,但是您可以对接口使用多重继承。使用委托模式,您可以将其他几个类的行为合并为一个。

Multiple class inheritance is not possible in Java, however you can use multiple inheritance for interfaces. Using Delegation pattern you can combine behavior of several other classes into one.

禾厶谷欠 2024-10-04 07:25:41

COM 中采用了完全不同的方法:所有对象都继承自 IUnknown,它有一个可以翻译为 Java 的方法:

Object queryInterface(Class<?> clazz)

最简单的实现可以是:

if(clazz.isAssignableFrom(this.getClass()))
    return this;
else
    return null;

如果单一继承不起作用,只需添加:

else if(class == SomeClass.class) {
    return something;
} else ...

该方法 即使是最复杂的多重继承情况也可以得到解决,并且您可以完全控制返回的内容和时间,因此您可以避免来自 C++ 等语言的“经典”多重继承的许多问题,例如 fork-join 问题。

Completely different approach is applied in COM: all objects inherit from IUnknown, which has a method that could be translated to Java as:

Object queryInterface(Class<?> clazz)

The simplest implementation of this method can be:

if(clazz.isAssignableFrom(this.getClass()))
    return this;
else
    return null;

Where single inheritance won't work, it's just enough to add:

else if(class == SomeClass.class) {
    return something;
} else ...

This way even most complex multiple inheritance cases can be tackled and you get full control over what is returned and when, so you avoid many problems with 'classical' multiple inheritance from languages like C++, like fork-join problem.

川水往事 2024-10-04 07:25:41

从 Java 1.8 开始,您可以使用带有默认方法的接口。它非常方便,我经常使用它。还支持协变返回类型。有一些限制(见下文),但您不必自己实现继承并让编译器为您工作。

public interface A {
    default A foo() {
        return this;
    }
}

public interface B extends A {
    @Override
    default B foo() {
        return this;
    }
}

public interface C extends A {
    @Override
    default C foo() {
        return this;
    }
}

public interface D extends B, C {
    @Override
    // if the return type does not implement B and C
    // the comiler will throw an error here
    default D foo() { 
        return this;
    }
}

请注意这一点,但请注意,您无法调用 super.foo 或定义字段或私有成员(直到 Java 9),因为它仍然是接口。如果您接受了这些限制,这将为您打开面向对象编程的新高度。

Since Java 1.8 you can use interfaces with default methods. It's very handy and I tend to use it a lot. Covariant return types are supported, too. There are a fiew restricktions (see below), but you dont have to implement the inheritence by your self and let the compiler work for you.

public interface A {
    default A foo() {
        return this;
    }
}

public interface B extends A {
    @Override
    default B foo() {
        return this;
    }
}

public interface C extends A {
    @Override
    default C foo() {
        return this;
    }
}

public interface D extends B, C {
    @Override
    // if the return type does not implement B and C
    // the comiler will throw an error here
    default D foo() { 
        return this;
    }
}

Note that this but note that you cant call super.foo or define fields or private members (until Java 9) since its still interfaces. If you get along with this restrictions, this opens up you a new level of object oriented programming.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文