Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain multiple inheritance in Java [duplicate]

Tags:

java

Actually the question was asking by one of the interviewer

Que: How can you say that java is not supporting multiple inheritance? If Object class is a parent of all classes in java.

I have no answer of that question.

That means no clear idea about java concepts :-(

Ex: if A extends B

And here A is already extending Object class. right? Now how its works?

Please share your answers..

like image 576
Sachin J Avatar asked Aug 20 '13 06:08

Sachin J


2 Answers

Multiple inheritance is about multiple-direct-inheritance.

A single class class can't have two immediate parent classes. It can have a grandparent class, though.

A extends B and B extends C, is not the same as A extends both B and C.

The reason this is disallowed is for simplicity when you have a case like:

A extends both B and C

B extends D

C extends D

If you had such a case, and then you had this code:

A a = new A();
a.someAbstractOrVirtualMethodOnD();

... are you talking about the B implementation of someAbstractOrVirtualMethodOnD(), or the C implementation of that same method? Which should get called? (Hint: there isn't a great answer)

So, Java bans it.

Note, you can get something much like multiple inheritance if you implement multiple interfaces. But since there is only one concrete implementation, there is no confusion as to what gets called.

like image 130
Merlyn Morgan-Graham Avatar answered Oct 07 '22 00:10

Merlyn Morgan-Graham


On the top of all to keep the language design simple

And the example from the blog I follow regularly.

enter image description here

1)We have two classes B and C inheriting from A.

2)Assume that B and C are overriding an inherited method and they provide their own implementation.

3) Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C?

Here we have an ambiguity.

Any ways to overcome this we have interfaces and Multilevel inheritance.

Edit :

And here A is already extending Object class.

That is never called as Multiple inheritance.That is called Multi level inheritance.

In Multi level ,

Many classes are involved in inheritance, but one class extends only one. The lowest subclass can make use of all its super classes' contents.

like image 42
Suresh Atta Avatar answered Oct 07 '22 01:10

Suresh Atta