Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance workaround in Java?

interface IA {
    public void a();
}

class AB implements IA {
    @Override
    public void a() { System.out.println("a"); } // <---.

    public void b() { System.out.println("b"); }
}

class C {
    public void c() { System.out.println("c"); }
}


// My class:
class AC extends C implements IA {
    @Override
    public void a() { System.out.println("a"); } // duplicate code 
}

public class Main {
    public static void main(String[] args) {
        AC ac = new AC();
        ac.a(); // "a"
        ac.c(); // "c"
    }
}

Using duplicate code does not seem to be a good idea, how could I design my class properly?

like image 683
user Avatar asked Dec 08 '22 07:12

user


2 Answers

You can use composition and delegate, among other options:

interface IA {
    public void a ();
} 

interface IB {
    public void b ();
}

class A implements IA {
    @Override public void a () { /* code */ }
}

class B implements IB {
    @Override public void b () { /* code */ }
}

class AB implements IA, IB {
    final A a = new A();
    final B b = new B();
    @Override public void a () { a.a(); }
    @Override public void b () { b.b(); }
}
like image 191
Jason C Avatar answered Dec 11 '22 11:12

Jason C


Java 8 introduces the concept of "default methods" - but before that you have no way around it.

like image 41
Nir Alfasi Avatar answered Dec 11 '22 12:12

Nir Alfasi