Sunday, March 12, 2017

Diamond Problem in Java

Have you ever  heard about Diamond Problem in java...♦♦???

Yes I'm sure you are ,  if you have ever come across with Object Oriented Concepts  applying in Java. Consideration of the Diamond Problem comes with one of the popular concepts of OOP which is called as the "Inheritance" in Java.

Don't worry if you are new to this and never heard about Diamond Problem. Let's start now..

What is Diamond Problem?

Diamond Problem is sometimes referred as the "Deadly Diamond of Death".

Simply it is an ambiguity that arises when two classes (class B , class C) inherit from a class (class A) and another class (class D) inherits from both B and C.

Have a look at this example if you still didn't get it..


Let's assume that Super class A is an abstract class and class B ,C and D are concrete classes.

Note:
Abstract class :  Base class or a Super class where only declared abstract methods and which does not provide implementations for all of its methods.
Concrete class : Derived class that provides the basic implementations for all of the methods that are not already implemented in the super class.

Here the ambiguity arises in class D when it tries to call Close() method. The compiler doesn't know from which class does it inherit as shown in the figure.

This is a serious problem for some other popular OOP languages like C++ that allows multiple inheritance while java doesn't allow multiple inheritance in classes.

Note:
Multiple Inheritance : Where class can inherit from more than one class

Consider the following situation related to above example.

Class_A.java

Class_A.java
Class_B.java




Class_C.java


Now let's assume Class_D implementation happens as below and it's extending both Class_B and Class_C.

Class_D.java




Here Class_D inherits from both Class_B and Class_C and both classes contain Close() method with different implementations.

In Class_D Test() method call to super class Close() method and this is the place where ambiguity occurred. Because compiler doesn't know which super class method to execute. This referred as diamond problem in Java and this is the main reason why java doesn't support multiple inheritance in classes.

How to Overcome Diamond Problem ?

To overcome this issue Java proposed the solution as Multiple Inheritance in Interface where a single interface can extend multiple interfaces.

Interface_A.java


Interface_B.java

Interface_C.java

Interface_D.java



This is perfectly fine because interfaces declare the methods and actual implementation will be done by concrete classes implementing the interfaces.So there is no possibility of having any kind of ambiguity in multiple inheritance in Java Interfaces.

That's why Java class can implements multiple inheritance like below,



Note: 
Here Class_D must implement the Close() method.If not compiler gives an error by saying you must implement the Close() method at Class_D.









No comments:

Post a Comment