In my early bachelor's degree when I was starting to begin familiar with languages like C and C++, Our teachers use to point us to this unique problem of multiple inheritance and how it causes ambiguity in the inherited class, the solution was to use virtual functions/inheritance, it seem to be a fix that was added to C++ as it was not thought earlier while designing the C++ language.
Later during my master's degree, this new language called "java" starting to pick up waves and I was kind of impressed with it earlier being a new language and always wanted to explore it. I remembered how C++ solved the problem of multiple inheritances, and was curious of how java would play with it.
Most of them believe that multiple inheritances are possible in java through java interface. However I have a difference in opinion here.
According to me inheritance is
- Inheriting the implementation
- Inheriting the declarations
Inheritance of implementation is inheriting the actual code that does the work when the method is called which is done in case of C++ multiple inheritance and which is not possible to do in case of java
Inheriting only the method declaration and variables for one or many such classes for which the implementation will be written in its subclass is called inheritance of interfaces which is a bit different from the concept of multiple inheritances and it’s only possible in java. An interface defines all of those methods that an object exposes to either its subclasses or other classes.
When you inherit from a class in Java you get both inheritance of interface and implementation. All methods in the super class become part of the subclass's interface. However, when you implement an interface you only inherit interface and must provide implementations for each method.
When a Java class implements multiple interfaces you do run the risk of naming clashes. A class can implement two interfaces that share the same method name and return type. Say for example you have the following interfaces:
public interface MyFirstInterface{
public void myFirstMethod();
}
public interface MySecoundInterface{
public void myFirstMethod();
}
A class called MyFirstInheritance can come and implement these two interfaces at the same time without difficulty. However there may be a problem. Chances are if this happens the resulting class with not be able to provide an implementation that satisfies the expected behavior of both the interfaces at the same time. Even if you go ahead and provide and implementation for myFirstMethod() this may not make sense if you simply view the object as an MyFirstInterface or MySecoundInterface.
So what's the solution? If you have access to the source code the best course of action is to rename the methods in either of the above cases. If you don't have access, you are stuck.