I have two interfaces. An interface A, and interface B, which extends interface A. Now, I have class which likes to keep reference of object that either implements A or B. And I would like to provide setter for it. I tried below, but getting type mis match exception.
public interface A {
}
public interface B extends A {
}
public class AB {
private Class<? extends A> object;
public void setObject(Class<? extends A> o){
this.object = o;
}
}
So basically, I would like setObject method to accept an object that either implements interface A or B.
Simple answer:
Type it as
A:setObject(A a).A class that implements
Balso implementsA. Full code:Now, if you really want to work with
B, you’d type it asB, which would also allow you to treat it as anA, sinceBinherits from it:But now you can’t pass an
A(static) reference tosetObject. If you really want to do this, then you’d need to first downcast it as aB, which could fail at runtime. Generics will not improve on this.