Reputation: 157
the setting is like this.
I have multiple interfaces (i.e. A,B,C) and I have classes (Z and Y) to implements them
X implements A,B{} and Y implements A,C{} and Z implements B,C{}
Some functions in interface A,B,C have the same definition and I don't want to retype them in each class, how should I do?
I did google it, and notice that one solution is to use a handy keyword default in the interface. But what if I am prohibited from using this keyword, like the code is compatible with version prior than Java8?
Is there a better way to handle this problem?
Upvotes: 1
Views: 847
Reputation: 179
Then you should go with abstract class and provide some default implementation for the common methods in different interfaces as below.
interface A {
void m1();
void common();
}
interface B {
void m2();
void common();
}
abstract class ABClass implements A, B {
public void common() {
System.out.println("Default");
}
Class X extends ABClass {
}
Upvotes: 1
Reputation: 266
Instead of gaining these methods through inheritance and having to extend mutliple classes to get your definitions in, you could favor composition and take a class that implements the method you want to reuse as a parameter. Keeping it as a private final member variable, you can call this common method in a generic way.
Upvotes: 1