I need to have a variable in a class which is an instance of class "ClassA" but which also implements interface "InterfaceI".
Obviously this can be done for one or the other easily:
private ClassA mVariable;
private InterfaceI mVaraible;
but how can I enforce the object both extends ClassA and implements InterfaceB? Something like:
private <? extends ClassA & InterfaceI> mVaraible;
is what I need but I have no idea of the syntax or if it is even possible. I will also need a get and set method, but that can be done with generics (I think?)
The obvious solution is
public class ClassB extends ClassA implements InterfaceI{
//whatever here
}
However both InterfaceI and ClassA are part of an external libary, this libary has classes which extend ClassA and InterfaceI and I cant edit them to make them extend ClassB, therefore this solution will not work.
I have found a rather hacky workaround.
The class contains both a ClassA and InterfaceI reference as follows:
private ClassA mItemClassA;
private InterfaceI mItemInterfaceI;
The set method then looks like this:
public void setVaraible(ClassA item){
assert (item instanceof InterfaceI);
mItemClassA = item;
mItemInterfaceI = (InterfaceI) item;
}
Other variations of this could be throwing an exception, returning false, etc if the item is not an instance of InterfaceI
Other methods in the class can then call functions from both InterfaceI and ClassA using mItemClassA and mItemInterfaceI.
I am not going to implement a get method for now, but if I did there would likely have to be a version to get the interface and a version to get the class.
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