Avoid duplicating method in two already extended classes that implement a common interface in java
I was asked this question in a java interview, but I couldn't find the answer anywhere.
X Y
| |
A B
Interface I{
m1();
}
Class A and Class B are extended from classes X and class Y respectively.
X and Y cannot be changed. Interface A and B i and method m1 () have the same definition in both.
How to avoid code duplication.
Java 8 cannot be used as we can define methods in java-8 interfaces.
Thanks in advance.
source to share
This is a terrible question, but a good way would be to make a static method (which contains m1 functions) in A.java
or B.java
, and just call that method in A#m1
and B#m1
.
This is much easier than creating another class.
A.java
@Override
public void m1() {
methodHelper();
}
public static void methodHelper() {
// Code goes here.
}
B.java
@Override
public void m1() {
A.methodHelper();
}
source to share
I agree with what Gabe Sechan has to say.
Let another class (class C) implement the m1 () method defined in the interface.
Class A and class B will have an instance of class C. This will allow you to use this m1 () method, where class C, implemented without class A and class B, has duplicate m1 () methods.
source to share