4
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?

3 Answers 3

11

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(); }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@JBNizet Thanks; I've been in C++ land all day.
3

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

2 Comments

Thats true but I still dont think we can call that multiple inheritance. There are still many restrictions for interfaces vs classes, like defining constructors , accessing variables other than local variables etc. Its sort of a compromise between mutiple inheritance and no multiple inheritance. But yes it definitely adds the problem of refrencing same method defined in both the interfaces.
@Mustafasabir agreed (and for the record, I never considered it as multiple inheritance)
0

You could make a a default method:

interface IA {
    public default void a(){ System.out.println("a"); }
}

1 Comment

This is a quick way but I really personally dislike that default methods were added to Java; the potential for making a mess when used improperly is very high. If you do this be sure to make sure you maintain a clear grasp on your code structure while developing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.