Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 493
user3620431 Avatar asked Jun 04 '26 20:06

user3620431


1 Answers

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();
}
like image 73
Jacob G. Avatar answered Jun 06 '26 11:06

Jacob G.