Java: Why multiple interfaces instead of multiple inheritance? [duplicate]

為{幸葍}努か 提交于 2019-12-04 19:12:04

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?"

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..

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!