Why multiple inheritance is not allowed in Java?

For long time I had a question “why Sun introduced Interface concept instead of C++ style of multiple inheritance?“. I did googling but many articles and forums talks about difference between abstract class and Interface not why Interface concept required in Java. After extensive search and analysis I came to know the reason behind the Interface concept in Java.

also read:

In C++ multiple inheritance is possible, virtual keyword is been used to define virtual function. Whereas in Java multiple inheritance is not possible however using Interface concept the same class can represent different structure.

Lets take an example in C++ where two parent class contains same virtual function.

Example:

class BaseCol
{
public:
virtual void a() { cout << "BaseCol::a" << endl; }
virtual void b() { cout << "BaseCol::b" < endl; }
};

class ChildCol1 : public BaseCol
{
public:
virtual void a() { cout << "ChildCol1::a" << endl; }
virtual void b() { cout << "ChildCol1::b" << endl; }
};

class ChildCol2 : public BaseCol
{
public:
virtual void a() { cout << "ChildCol2::a" << endl; }
virtual void b() { cout << "ChildCol2::b" << endl; }
};

class Row : public ChildCol1, public ChildCol2
{
public:
// i want to overide the b function of ChildCol1 only !!
void b() { cout << "Row1::b" << endl; }
};

While executing the above code at runtime ambiguity error will occur since the implementation has conflicting methods. This problem is called Diamond inheritance problem.

To avoid this complexity Java provides single inheritance with interface concept. Since interface cannot have method implementation, the problem is therefore avoided since there is always only one implementation to a specific method and hence no ambiguity will arise.

Every concept/ design is to solve specific problems not to create magics.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>