继承的选择

发布于 2024-07-10 12:55:00 字数 36 浏览 7 评论 0原文

除了实现接口之外,我们还可以使用什么其他选项来实现多重继承

Whats the other option we can use for multiple inheritance other than implementing interface

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

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

发布评论

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

评论(4

白况 2024-07-17 12:55:00

直接的答案是使用内部类。 这为您提供了两个(或更多)紧密链接但覆盖独立基类的对象。

一般来说,更喜欢组合而不是继承。 到处使用继承是一个常见的错误。 然而,这留下了难以遵循的不灵活的解决方案。

A direct answer is to use inner classes. That gives you two (or more) objects that are intimately linked but cover independent base classes.

In general, prefer composition over inheritance. It's a common mistake to use inheritance everywhere. However, that leaves inflexible solutions that are difficult to follow.

天煞孤星 2024-07-17 12:55:00

首先,最好避免多重继承并使用接口。 而Java实际上并不支持多重继承。

但是你可以使用 mixins 来伪造多重继承。 有一些关于此的手册:

Java 中的多重继承

Java Mixin 模式,或伪造多重继承

和如果你想做一些复合的东西,我建议看看 Qi4j 框架:

使用 Qi4j 进行面向组合编程

At first, it's better to avoid multiple inheritance and use interfaces. And Java actually does not support multiple inheritance.

But you can use mixins to fake the multiple inheritance. There are some manuals about this:

Multiple Inheritance in Java

The Java Mixin Pattern, or Faking Multiple Inheritance

And if you want to make something composite, I advise to take a look at the Qi4j framework:

Composite Oriented Programming with Qi4j

猫七 2024-07-17 12:55:00

Java 没有多重继承

接口 页面 Java 教程

Java 编程语言没有
允许多重继承
...,但接口提供
另一种选择。

由于一个类可以实现多个接口,因此可以用作 Java 中实际多重继承的替代或替代。

Java does not have multiple inheritance.

From the Interfaces page of The Java Tutorials:

The Java programming language does not
permit multiple inheritance
... , but interfaces provide
an alternative.

Since multiple interfaces can be implemented by a class, that can be used as a substitution or alternative to having actual multiple inheritance in Java.

你对谁都笑 2024-07-17 12:55:00

您可能必须使用组合 - 即,将“父”类的实例作为“子”类的成员。 (这里的“父”和“子”表示如果您使用继承,两个类将具有的关系。)然后,包含(“子”)类必须包装所包含(“父”)类的接口以公开任何功能 平滑包装过程的

一种方法是让包含类和包含类都实现相同的接口 - 然后,包含类中该接口的方法的实现可以直接调用包含类上的相同方法。

You'll probably have to use composition - i.e., having an instance of your "parent" class as a member of your "child" class. ("Parent" and "child" here indicate the relationship the two classes would have if you were using inheritance.) The containing ("child") class must then wrap the interface of the contained ("parent") class to expose any functionality of the contained class

One way to smooth the wrapping process is to have both the contained and containing class implement the same interface - the implementations of the methods of this interface in the containing class can then be straight calls to the same methods on the contained class.

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