扩展两个类
我有两个类 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,短语“组合优于继承”实际上很适合......
我会创建一个结合了我想要适应的两个类的功能的接口。
然后我将创建一个实现我的新接口的类。该类将包含 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.
组合(“基”类中至少一个,可能两个都是成员对象) 。以及根据需要提供的大量代理(一些编辑器会在这里为您提供帮助)。
雅虎 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.
你可以使用组合。让您的类将其中一个(或两个)作为字段,并将其方法公开为传递方法。
You could use composition. Have your class have one (or both) as fields and expose their methods as pass-through methods.