Resolving Diamond Problem:-
Diamond problem occurs when we try to use “Multiple inheritance ” through classes.
Assume there are parent classes A and B and a child class C.
So, C extends A & B. Assume there are two non-static methods in both the parent class having
the same method name i.e m1 method.
The child class C acquires both the properties of A and B. Hence both the m1() methods from A
and B will be inherited in the child class C.
Creating an object of child class and then calling the m1() method, compiler faces “Ambiguity”
or confusion on which m1() method to call. This leads to a diamond problem and that’s the
reason why it cannot be achieved with classes.
class A
{
public void m1()
{
[Link](“Parent-1 Method”);
}
}
class B
{
public void m1()
{
[Link](“Parent-2 Method”);
}
}
class C extends A,B
{
public static void main(String[] args)
{
C c = new C();
c.m1(); // compiler faces ambiguity leading to diamond problem
}
}
The above problem can be overcome or resolved by using interfaces. Hence multiple
inheritance can be achieved with the help of interface.