Avoid duplicate method in two already extended classes implementing common interface in java

时间:2017-04-10 00:48:30

标签: java inheritance

I have been asked this question in a java interview but I could not find the answer anywhere.

X Y
| |
A B

Interface I{
m1();
}

Class A and Class B are extended from Class X and Class Y respectively.

X and Y cannot be changed. A and B implement interface I and method m1() has same definition in both.

How to avoid writing duplicate code.

Java 8 cannot be used since we can define methods in java-8 interfaces.

Thanks in advance.

2 个答案:

答案 0 :(得分:2)

This is an awful question, but a good way to go about it would be to make a static method (which holds the functionality of m1) in either A.java or B.java, and simply call that method in A#m1 and B#m1.

This is a lot more simple than having to create another class.

A.java

@Override
public void m1() {
    methodHelper();
}

public static void methodHelper() {
    // Code goes here.
}

B.java

@Override
public void m1() {
    A.methodHelper();
}

答案 1 :(得分:0)

I agree with what Gabe Sechan has to say.

Have another class (Class C) implement the m1() method defined in the interface.

Class A and Class B will both have an instance of Class C. This will allow you to use that m1() method in which Class C implemented without having Class A and Class B have duplicate m1() methods.