Tuesday, June 8, 2010

Why Multiple Inheritance is not supported in java using classes

Why Multiple inheritance is not possible in java using classes means that it can be achieved using something else. We can use interfaces to make multiple inheritance possible in java.

Let us first discuss why its not possible with classes using a simple example

Let us assume we've two programmers A and B

A has written a class named ClassA which is inheriting ClassSuper and overriding one of its methods called Hello()

B has written a class named ClassB which is inheriting ClassSuper and overriding one of its methods called Hello()

Now, if multiple inheritance is allowed in java, another programmer called C wanted to extend both the clasess ClassA and ClassB which are written by A and B programmers respectively.

He is not overriding the method Hello() in his class. What if he calls method Hello()?

How does Java Virtual Machine(JVM) know which Hello() method (from ClassA or ClassB) to call?

This is the reason why multiple inheritance is not possible in java. But, still it can be achieved using interfaces. One must implement all the methods presented in interface if he is implementing interface. So, there is no possibility of confusion that which method to call, because java doesn't allow same method signatures in one class or interface.

No comments:

Post a Comment