Saturday, July 12, 2014

Does Java support Multiple Inheritance?

Answer to this question is yes, java does not support multiple inheritance but by introducing the concept of interface it just gives the feeling of multiple inheritance but still it is not multiple inheritance.

Multiple inheritance means inheriting more than one class into single class. A class may implement more than one interface but it can inherit only one class. Interface does not contain method implementation but it contains abstract methods which need to be implemented by the class which uses that interface. So it just gives feeling of multiple inheritance but it is not multiple inheritance as the class which uses those interfaces must implement the methods present in those interfaces.

Multiple inheritance gives rise to diamond problem. Let us see that this problem is.

In the above diagram, two classes B and C are derived from same class A and class D is derived from two classes B and C using multiple inheritance. The problem with above type of inheritance is that when an instance of D is calling any method of class A, it is not clear whether to call version of method derived from class B or class C. You can see in the figure above that the classes essentially form the shape of a diamond, this problem is called the diamond problem.

In the designers' opinion, multiple inheritance causes more problems and confusions than it solves. The use of multiple inheritance results into diamond problem so for the sake of simplicity, multiple inheritance is not supported in java. 

No comments:

Post a Comment