Reputation: 2403
I have this confusion for long time. Many people says we can achieve multiple inheritance by interfaces in languages like C# or Java which does not support it like C++ does. But my understanding of inheritance and interface says no. Because interfaces are contracts to validate an implementation which has nothing to do with behavior. Interface defines what something can do (not what something is). But inheritance is inheriting behavior and/or property from parents (like a child is getting some genetic behavior from his parent - which is inheritance). Now the child is learning a skills say painting and cooking and the interface (a certificate or contract) acts as a validation that the child is having such skills (that is what the child can do other than what he got from his parents - and that's not inheritance)
So am I understanding it wrong? And if not then why it is saying that we can achieve multiple inheritance using interfaces?
Upvotes: 2
Views: 102
Reputation: 2647
No, interfaces cannot be used to achieve multiple inheritance
Not at all in Java, in C#, we can get closer.
I studied this matter when I wanted to implement an observer, and ended up in Robert Martin's blog: http://blog.cleancoder.com/uncle-bob/2015/01/08/InterfaceConsideredHarmful.html
After reading this post I realized he's talking about Java, but C# supports extension methods which allow you to attach behaviour on interfaces so I tried to make my implementation on some IObservable interface but obviously failed, even if I can attach behaviour in such interfaces extension methods I'm still not allowed for attaching state on them, if some day microsoft decides to implement extension properties then this combination (Interface + Extension methods + Extension properties) could be sufficient to truly simulate some useful multiple inheritance.
For now, we are stuck with duplicating the code, or the delegation code in all our observers as stated in the blog.
Upvotes: 0
Reputation: 2593
In Java you can create an interface for example Animal
and an abstract class Bird
.
then you can have a class MockingBird
which extends the behavior of Bird
and implements the actions of an Animal
.
However, you can then address MockingBird
as an Animal
or as a Bird
because it "inherits" from both.
Upvotes: 0
Reputation: 73568
Interfaces give you multiple inheritance of a type, but not behaviour. A class implementing List
and Map
is a "ListMap", but the implementation has nothing (necessarily) to do with any existing List
or Map
implementation.
Of course using composition (which should be favored anyways), you could easily create a ListMap
which delegates the calls accordingly to its list
and map
properties, while providing some presumably useful function that would combine their respective data.
With Java 8 interfaces are allowed default methods, so inheritance of behaviour is now also possible.
Upvotes: 3