Foren » Discussions » Why can I not use multiple inheritances in java?

jamesalter
Avatar

There was an instance where during the screening process, the client asked a java code developer why multiple inheritances cannot be used in Java. Now, while we are aware that we cannot use multiple inheritances in java, the ‘why’ is often the part we do not focus on.

The first, and probably the most important reason is that it creates ambiguity around the diamond problem. Take a situation where class A has a foo() method, and thereafter, class B and C are derived from class A. Now, these two classes have their foo() implementations. After this, D is derived from B and C, and the process used is multiple inheritances. Here, if we refer to just foo(), the compiler would be confused and wouldn’t be able to decide which foo() is to be involved. Since the structure of this inheritance situation is similar to a four-edged diamond, the name diamond problem is given.

Now, as a Java code developer, you may wonder that if C++ can support multiple inheritances, then why not Java?

This is because the design is complicated with the use of multiple inheritances. As a result, there are problems during casting, constructor chaining, etc. Moreover, there are not several instances where we need multiple inheritances. Keeping all this in mind, it is best to omit it altogether to ensure that simplicity is maintained.

To add to it, Java does avoid this ambiguity by offering single inheritance with interfaces. The interface doesn’t provide any implementation. It just has a method declaration. Thus, there will be a single implementation of a specific method. This would ensure the absence of ambiguity of any sort.

As a freelance Java code developer at Eiliana, you must know the reason behind the various workings of the language. This will help you serve your clients in a much better way. You can also save yourself from various bugs and solve an existing issue in no time if you are aware of the reasons along with the workings.