I have one main interface and an abstract class implementing all "derivable" methods (that can be written using only abstract methods) of it:
public interface Main {
public void main1(int x);
public void main2();
}
public abstract class MainAbstract implements Main {
public void main2() { main1(42); }
}
This functionality can be extended in different "directions":
public interface SubA extends Main {
public void subA1(int x);
public void subA2();
}
public interface SubB extends Main {
public void subB1(int x);
public void subB2();
}
Now I could have abstract classes SubAAbstract
and SubBAbstract
implementing all the "derivable" methods (like main2
in Main
). The problem is that I may have concrete implementations who want to implement both SubA
and SubB
, so I could use only one of the abstract classes. In reality the problem is worse, because I have more than 2 sub-interfaces.
I'm aware that there is no way around single inheritance in Java, but I would like to know if there is a good way to minimize code duplication in that case.
[Edit]
Would it be an abomination to put all functionality in the MainAbstract class (note that it only implements Main), e.g.
public abstract class MainAbstract implements Main {
public void main2() {
main1(42);
}
public void subA1(int x) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void subA2() {
subA1(4711);
}
public void subB1(int x) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void subB2() {
subB1(-1);
}
}
Then a concrete class needs just to implement the needed interfaces, and to implement the needed methods:
public class MainConcrete extends MainAbstract implements Main, SubA {
public void main1(int x) {
System.out.println("main " + x);
}
public void subA1(int x) {
System.out.println("subA" + x);
}
}
Of course this would only make sense if the hierarchy is rather stable (that means, the sub interfaces are known exactly before), but this would be the case for me. Having the superfluous methods visible isn't nice either, but I don't seee a way to change that.