java how can I overcome multiple inheritance and diamond problam

479 views Asked by At

I'm trying to understand how can I overcome the "diamond problem" in JAVA let's say I have these 3 interfaces:

interface Alpha{
    public default int methodA() {
        int result=0;
        System.out.println("Print from Alpha methodA");
        return result+4;
    }
}

//**********************************

interface Betta extends Alpha {
    public default int methodA() {
        int result=0;
        System.out.println("Print from Betta methodA");
        return result+8;
    }
}
//*******************************

interface Gamma extends Alpha {
    public default int methodA() {
        int result=0;
        System.out.println("Print from Gamma methodA");
        return result+16;
    }
}

And that class:

public class Delta implements Betta,Gamma {
    public static void main(String args[]) {
    // TODO Auto-generated method stub

    Delta cObj=new Delta();
    cObj.methodA();
}

how can I get class Delta giving me the output of Alpha interface? Any other way than changing it to "Delta implements Alpha"?

2

There are 2 answers

4
Rohit Gulati On

If you are implementing Betta and Gamma in class Delta then you must be getting compilation error in Delta to override default method. Because if two interfaces have same default method then the class implementing both must define its own implementation.

You can do it like :

public class Delta implements Betta, Gamma {
    public static void main(String[] args) {
        Delta cObj = new Delta();
        cObj.methodA();
    }

    @Override
    public int methodA() {
        return Betta.super.callSuperMethodA();
    }
}

public interface Betta extends Alpha {

    public default int methodA() {
        int result = 0;
        System.out.println("Print from Betta methodA");
        return result + 8;
    }

    //Call this from Delta default method
    public default int callSuperMethodA() {
        return Alpha.super.methodA();
    }

}
0
Damir Bar On

You can either turn Alpha's method to static

public interface Alpha {
public static int methodA(){
    int result = 0;
    System.out.println("Print from Alpha methodA");
    return result+4;
}}

or you can create a method referring to Alpha's method in Betta or Gamma.

A third optional solution to this would be deleting both Gamma's and Betta's default implementations, meaning emptying both of them intirely.