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.
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();
}
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