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?
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(); }
}
Java 8 introduces the concept of "default methods" - but before that you have no way around it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With