Java:为什么使用多个接口而不是多个继承? [英] Java: Why multiple interfaces instead of multiple inheritance?

查看:155
本文介绍了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

为什么不是从多个类(Java不允许)继承,为什么要告诉我们实现多个接口呢?

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?

推荐答案

多重继承会导致多种问题.

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.

不能保证两个类 实施相同的一套 接口将提供相同的 功能-还是我想念 什么?"

"There's no guarantee that two classes implementing the same set of interfaces will provide the same functionality - or am I missing something?"

关于您的上述声明:

每个方法都应遵守合同,因此,无论您如何实现它,如果应该这样做,则该方法的功能应始终相同.如果它违反了合同,则意味着它被错误地实施了.

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.

这篇关于Java:为什么使用多个接口而不是多个继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆