Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Inheritance in java

Java is not allowing inheritance from multiple classes (still it allows inheritance from multiple interfaces.), I know it is very much inline with classic diamond problem. But my questions is why java is not allowing multiple inheritance like C++ when there is no ambiguity (and hence no chances of diamond problem) while inheriting from multiple base class ?

like image 505
Silent Warrior Avatar asked Aug 11 '09 19:08

Silent Warrior


People also ask

Why multiple inheritance is not possible in Java?

The reason behind this is to prevent ambiguity. Consider a case where class B extends class A and Class C and both class A and C have the same method display(). Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.

Is multiple inheritance possible in Java Explain with examples?

When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn't allow multiple inheritance.

Why multiple inheritance is used in interface?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class.

What is multiple inheritance inheritance?

Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or class may only inherit from one particular object or class.


2 Answers

It was a design decision of Java. You'll never get it, so don't worry too much about it. Although MI might help you make Mixins, that's the only good MI will ever do you.

like image 111
Randolpho Avatar answered Nov 15 '22 15:11

Randolpho


I have read that most programmers don't use multiple inheritance in a proper way. "Just go ahead and inherit from a class just to reuse code" is not the best practice in case of multiple inheritance.

Many programmers do not know when to use simple inheritance in most cases. Multiple inheritance must be used with caution and only if you know what you are doing if you want to have a good design.

I don't think that the lack of multiple inheritance in java (as in c++) will put restrictions in your code / application design / problem domain mapping into classes.

like image 37
Andreas Avatar answered Nov 15 '22 16:11

Andreas