Reputation: 240
I need to define 4 interfaces with names and methods as given in the first picture.
But, I need to maintain the following relationship:
So, I modified the interfaces with inheritance as shown below:
But the problem is, AnimalMutable is getting two instances of "GetLifeSpan()" methods (one from AnimalConst and another from LivingBeingMutable). Could anyone let me know what is the correct way to design it?
Upvotes: 2
Views: 74
Reputation: 6015
This is a famous multiple inheritance problem called "The Diamond Problem".
You need concepts such as virtual base classes - "Virtual Inheritance" (C++).
For more information, look here:
http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
http://www.learncpp.com/cpp-tutorial/118-virtual-base-classes/
You could either try to use single inheritance, as almost concepts done with multiple inheritance can be also done with single inheritance, and there are many widely used OOP Languages that support only single inheritance.
Other languages do not support pure multiple inheritance but provide alternative mechanisms to get some of the benefits of the multiple inheritance and avoid such problems instead. Interfaces in Java is one such mechanism, as you just define the signature methods and the implementation is always responsibility of the class that implements them, although a class could implement many interfaces.
Upvotes: 2
Reputation: 7057
This would have been a diamond problem in c++.
If you are using Java / C# (guessing from your mention of interface) you should not have any problem.
Interfaces were invented to solve the diamond problem.
In stead of method prototype, if you had a member variable being inherited, the question of "where did it come from" would have been meaningful.
Since it's just prototype of a method (it's same anyways), it does not matter if the same method is being inherited from multiple interfaces. So you can safely create those interfaces without any problem.
Hope this helps.
Upvotes: 0