Sunday, 10 April 2016

Why Java does not support multiple Inheritance ?


Java does not support multiple Inheritance (unlike, C++)

  • Reason : Deadly Diamond of Death
  • The class diagram formed in this scenario is a diamond
  • It's a no solution output, so the code gets locked
  • Java support multiple implementations, but not multiple Inheritance.
    • A class can implement many Interfaces, but can not extend more than one class.
  • Example
    1. An abstract super class, with an abstract method in it.

    2. Now 2 concrete class extend this abstract super class, and provides the implementation of the abstract method in the super class.

    3. A 4th class which extends the above two concrete classes.


    So now by the principle of inheritance it inherits all the methods of the parent class, but we have a common method in the two concrete classes but with different implementations, so which implementation will be used for the last child class which inherits both these classes ?


    Actually, no one has got the answer to the above question, and so to avoid this sort of critical issue, Java banned multiple inheritance.


Example

// Top most abstract class
class AbstractSuperClass{
    abstract void do();
}

// 2 concrete sub classes which extend the above super class
class ConcreteOne extends AbstractSuperClass {
   void do(){
      System.out.println("I am going to test multiple Inheritance");
   }
}

class ConcreteTwo extends AbstractSuperClass {
   void do(){
     System.out.println("I will cause the Deadly Diamond of Death");
   }
}

// Last class which extends both of the above concrete classes
class DiamondEffect extends ConcreteOne, ConcreteTwo {
   //Some methods of this class
}


No comments:

Post a Comment

Note: only a member of this blog may post a comment.