1.

Why Java doesn’t support multiple inheritance?

Answer»

An important part of object-oriented programming is MULTIPLE INHERITANCE. This means that a class INHERITS the properties of multiple classes.

However, multiple inheritance may lead to many problems. Some of these are:

  • The diamond problem occurs when 2 classes (B and C) inherit from a SINGLE class(A) and then a class(D) inherits these 2 classes (B and C) using multiple inheritance. This leads to multiple copies of class members of class A in class D which can create problems.
  • The ambiguity problem occurs if a class inherits from 2 classes that CONTAIN the same name for a class member. Then there is ambiguity in the inherited class when that class member is required.

The above problems are one of the reasons that Java doesn't support multiple inheritance.

A program that demonstrates the diamond problem in Java is given as follows:

public class A {    void display()    {        System.out.println("This is class A");    } } public class B extends A {    void display()      {        System.out.println("This is class B");    } } public class C extends A {    void display()    {        System.out.println("This is class C");    } } public class D extends B, C {   public static void main(String args[])   {       D obj = new D();       D.display();   } }

The above program leads to an error as multiple inheritance is not allowed Java.



Discussion

No Comment Found