1

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?

3
  • 4
    Can you describe the problem more clearly? If A, B and C all share a method named f with the same signature, and W implements all three interfaces, you still just need to write the implementation once. Commented Oct 15, 2018 at 16:38
  • You should consider using java 8 or even 11 since older versions are not supported by Oracle and most people have migrated to java 8 or 11. Commented Oct 15, 2018 at 16:40
  • let A has functions: a1,a2,a3 B has b1,b2,b3 C has c1,c2,c3 a1, b1 and c1 have the same definition, otherwise different definition Commented Oct 15, 2018 at 16:42

2 Answers 2

1

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

Comments

1

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.

1 Comment

won't this make the code less comprehensible? I am still learning OOP, can you provide me a simple example? thank.

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.