Question is; if Java or .Net supports multiple inheritance through Interfaces, why not through classes. He also did argue saying… it’s said that multiple inheritance is not supported due to the conflicts could be caused due to having the same method name in more than one parent class. But… it is possible to have the same method name in more than one interface and implement them in a one class with no conflict. So why not have the same mechanism for multiple inheritance through classes.
At first it’s confusing. Second, it’s a stupid question... but; still a good question to be asked in an interview….
For the benefit of those who having the same doubt, here is the answer.
Yes... it’s true; there can be method name conflicts in multiple inheritance. So how do interfaces escape from this?
Quite simple… Though we have the same method name in two different interfaces, we have only one implementation in our class, which implements both the interfaces.
So no conflict in finding the method. The object of this class can be a type of either interface, but when we call a method on the object; it will point to the method implemented in the class. Interfaces cannot carry method implementations.
For more information.. James Gosling writes in the white paper "The Java Language Environment", published in May 1996, under the section "Features Removed from C and C++" as ;
2.2.5 No More Multiple Inheritance
Multiple inheritance--and all the problems it generates--was discarded from Java. The desirable features of multiple inheritance are provided by interfaces--conceptually similar to Objective C protocols.
An interface is not a definition of a class. Rather, it's a definition of a set of methods that one or more classes will implement. An important issue of interfaces is that they declare only methods and constants. Variables may not be defined in interfaces.
Now, I think I understand why they removed it. If a person can't understand why it's dangerous - it's dangerous to let that person use it. But I think it's a usefull feature if used wisely
ReplyDelete