Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member variable which must extend class A and implement some interface

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.

like image 246
jtedit Avatar asked Nov 01 '22 09:11

jtedit


1 Answers

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.

like image 173
jtedit Avatar answered Nov 15 '22 04:11

jtedit