Why multiple inheritance is not allowed in Java?

SHARE & COMMENT :

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.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Jyoti Shrivastav says:

    great thanks for the clear explaiation & the reference that makes it easy to understand…!!

  2. Joe Porter says:

    Lovely post! This page was also helpful in understanding why multiple inheritance is not allowed in Java:

    http://www.programmerinterview.com/index.php/java-questions/multiple-inheritance/

  3. Debashis Sarkar says:

    bullshit post . if the parent classes have 2 different methods still it shows an error . Why it shows error then ??

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better