Java:为什么使用多个接口而不是多重继承?
可能的重复:
为什么Java允许多重继承来自接口,但不来自抽象/具体类
为什么 Java 中没有多重继承,但允许实现多个接口
为什么我们被告知要实现多个接口而不是从多个类继承(Java 不允许)?
当然,从多个类继承的要点是继承它们的功能 - 如果您必须手动重新插入功能(对于扩展一组接口的每个类),那么使用接口的意义何在?无法保证实现同一组接口的两个类将提供相同的功能 - 或者我错过了什么?
Possible Duplicates:
Why does Java allow multiple inheritance from interfaces but not from abstract/concrete classes
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed
Instead of inheriting from multiple classes (which Java doesn't allow), why are we told to implement multiple interfaces instead?
Surely the point of inheriting from multiple classes is the inherit their functionality - if you have to manually re-insert functionality (for each class extending a set of interfaces) what's the point of using the interfaces? There's no guarantee that two classes implementing the same set of interfaces will provide the same functionality - or am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
多重继承可能会导致多种问题。
接口用于为实现它们的类的实例提供能力。我个人使用具有组合的接口(使用引用其他对象的实例变量),以便为我的类提供原本可以通过多重继承实现的功能。
换句话说,我的类提供了所实现的接口所承诺的功能,但在内部我的类实例使用实例变量来完成这项工作。
关于您上面的陈述:
方法都应该遵守合同,因此无论您如何实现它,如果这是应该做的,该方法的功能应该始终相同。如果它违反了合同,则意味着它是实施错误。
Multiple inheritance is something that can cause multiple problems.
Interfaces are used to give abilities to instances of the class that implement them. I personally use interfaces with composition(using instance variables that are references to other objects) in order to provide functionality to my class that would otherwise be achieved with multiple inheritance.
In other words my class provides the functionality promised by the interface implemented but internally my class instance uses the instance variable to do the job.
About your statement above:
Each method should adhere to a contract so no matter how you implement it the functionality of the method should always be the same if this is what is supposed to do. If it breaks the contract it means it was implemented wrongly.
多重继承可能会导致循环继承..以避免我们采用基于接口的继承..
multiple inheritance may lead to cyclic inheritance.. to avoid that we are going for interface based inheritance..
您应该阅读有关钻石依赖问题的内容 http://en.wikipedia.org/wiki/Diamond_problem为了避免这种情况,Java 选择了接口而不是多个类的扩展
You should read about the diamond dependency problem http://en.wikipedia.org/wiki/Diamond_problem and to avoid this Java chose interfaces over extension of multiple classes