15 Jun 2015

Why java does not support multiple inheritance?

Multiple inheritance can be really difficult to understand. When you have a multiple inheritance with two classes which have methods in conflicts, how do you handle this ?
Of course solutions exist (in C++ for example) but the creators of Java decided it was way to complicated and not really in the Java philosophy (make development a lot easier).
From sun.com :
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.

Multiple Inheritance is :
  • hard to understand
  • hard to debug (for example, if you mix classes from multiple frameworks that have identically-named methods deep down, quite unexpected synergies can occur)
  • easy to mis-use
  • not really that useful
  • hard to implement, especially if you want it done correctly and efficiently
  1. Assume that class A is having a method fun(). class B and class C derives from class A.
  2. And both the classes B and C, overrides method fun().
  3. Now assume that class D inherits both class B, and C. (just Assumption)
  4. Create object for class D.
  5. D d = new D();
  6. and try to access d.fun();  will it call class B's fun() or class C's fun()?

Therefore, it can be considered a wise choice to not include Multiple Inheritance into the Java language.
Problem with multiple inheritance: Diamond problem.
Example:
This is the ambiguity existing in diamond problem.It is not impossible to solve this problem, but it creates more confusion and complexities to the programmer while reading it. It causes more problem than it tries to solve.

1 comment:

  1. Thank you for sharing this knowledgeable post its very helpful apart from that if anyone looking for best Core and Advanced Java training institute in delhi so contact here +91-9311002620 visit https://www.htsindia.com/java-training-courses

    ReplyDelete