Say I have several interfaces that all extends from a parent interface. The parent interface has some members that must be used by all child interfaces, so normally I would like to add a constructor in the parent interface to setup these common members. But this cannot be done as the classes are interfaces, not abstract classes. And I cannot simply change them to abstract classes because I would allow a class to implement multiple interfaces, which cannot be done using abstract classes. How do you resolve this yet ensuring the design requirements?
e.g.
interface Parent {
SomeCommonMember commMember;
Parent(SomeParameter para) {
// do some calculations to init commMember based on para
commMember = ...;
}
}
interface ChildA extends Parent {
void ChildAMethod();
}
interface ChildB extends Parent {
void ChildBMethod();
}
public class MyImplementation implements ChildA, ChildB {
MyImplementation(SomeParameter para) {
super(para);
};
void ChildAMethod() {
// uses commMember
};
void ChildBMethod() {
// uses commMember
};
}
public class Test {
public static void main(String[] args) {
Parent generic = new MyImplementation(new SomeParameter());
if (generic instanceof ChildA) {
generic.ChildAMethod();
}
if (generic instanceof ChildB) {
generic.ChildBMethod();
}
}
}