Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Inheritance :Java vs C++

Recently ,after reading some articles in Programming Languages and Practice book ,it is mentioned that multiple interface inheritance in Java does not suffer from the same problems as multiple class inheritance in C++.

But I can't understand why this happens. How java is able to use multiple interface inheritance while in C++ implementation errors exists ??

Is there a way to replace multiple inheritance in C++ as to avoid implementation problems ??

For the last statement to be more specific ,lets say that we have:

class A {...};
class B : public A {...};
class C : public A {...};
class D : public B, public C {...};

Then class D inherits class B,C which both inherit class A. So if A had a field-variable then B,C would have the same variable name ,then what variable would D has (inherited from B or C) .To avoid this could we write the above code without multiple inheritance but with similar results?

The question is not a duplicate since it is not focused on what finally will be the inheritance in the example ,but to understand the difference between Java-C++ multiple inheritance(see the first question above) and also if there is a way suggested to overcome some multiple inheritance problems (like the above).

like image 904
coder Avatar asked Dec 24 '22 01:12

coder


1 Answers

Java (unlike C++) does not allow multiple inheritance of state and, therefore, does not suffer from a diamond problem.

It allows multiple inheritance of type through interfaces (a class can implement multiple interfaces).

Starting with Java 8 there is also multiple inheritance of behavior through default methods in interfaces.

like image 50
PM 77-1 Avatar answered Dec 26 '22 14:12

PM 77-1