扩展两个类

发布于 2024-09-30 11:16:44 字数 106 浏览 1 评论 0原文

我有两个类 ModalWinodw 和 SkinnableWindow 都扩展了 Window 类。我想创建一个具有两个类的功能的类,但在 Java 中,类只能扩展一个超类。那么如何解决这个问题呢?

I have two classes ModalWinodw and SkinnableWindow both are extending Window class. I want to create class that has function from both classes, but in Java class can extends just one superclass. So how to solve this?

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

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

发布评论

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

评论(3

爺獨霸怡葒院 2024-10-07 11:16:44

在这种情况下,短语“组合优于继承”实际上很适合......

我会创建一个结合了我想要适应的两个类的功能的接口。

然后我将创建一个实现我的新接口的类。该类将包含 ModalWindow 和 SkinnableWindow 的实例。根据调用的功能,我的类将简单地将方法调用传递给适当的类,并在需要时利用每个类的功能。

This is a case where the phrase "Composition over Inheritence" actually fits...

I would create an interface that combines the functionality of both classes that I want to fit.

I would then create a class that implements my new interface. That class would contain an instance of both ModalWindow and SkinnableWindow. Depending on what functionality is called, my class would simply pass the method call on to the appropriate class, leverage each class' functionality when needed.

冷情 2024-10-07 11:16:44

组合(“基”类中至少一个,可能两个都是成员对象) 。以及根据需要提供的大量代理(一些编辑器会在这里为您提供帮助)。

雅虎 Java OO!

编辑:虽然组合在这里是“可行的方法”(无需重新设计类层次结构),但它有一些特定的限制,具体取决于接口和主名的使用方式。如果您需要在任何地方传递“特定”类型(ModalWindow 或 SkinnableWindow),您几乎会陷入困境,因为您的新类最多可以将其中一个作为祖先(因此,如果它是一个或更少,您可以能够溜过去)。使用接口并尽可能通用地了解类型可以减少这种伤害。

快乐编码。

Composition (at least one, possibly both, of the "base" classes would be a member object). And lots of proxies as needed (some editors will help you here).

Yahoo Java OO!

Edit: While composition is "the way to go" here (without redesigning the class hierarchy), there are some specific limitations with it depending upon how interfaces and nominative names are used. If you need to pass the "specific" type (ModalWindow or SkinnableWindow) anywhere you're pretty much in a world of hurt as your new class can have at most one of them as an ancestor (so if it's one or less, you may be able to slip by). Using interfaces and being as general about types as possible can reduce this hurt.

Happy coding.

(り薆情海 2024-10-07 11:16:44

你可以使用组合。让您的类将其中一个(或两个)作为字段,并将其方法公开为传递方法。

You could use composition. Have your class have one (or both) as fields and expose their methods as pass-through methods.

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