I am a little confused with something.
I have a class where its not a collection, but it does refer to generic objects:
public class XClass<E extends AnInterface>{
E instanceobject;
public void add(E toAdd){}
}
public interface AnInterface{}
public class A implements AnInterface{}
public class B implements AnInterface{}
I believe I read somewhere that <? extends AnInterface> is to be used (when declaring an instance of XClass) if you want multiple subtype-types in the generic object at the same time, whereas <T extends AnInterface> would only allow you to have a single type of subtype in the generic class at once?
However, I can just use:
XClass<AnInterface> xc = new XClass<AnInterface>();
A a = new A();
B b = new B();
xc.add(a);
xc.add(b);
and this way I can pass in multiple subtypes of Supertype to the generic class……
I am not seeing the purpose of using “?” and is there anything wrong with using the Interface as the generic parameter?
The reason why you can add objects of both type
AandBis due to the fact that you parametized your XClass with the interface, so there is nothing wrong with adding two different classes that implement that interface.If, on the other hand, you had defined XClass as:
then the expression
xc.add(b);would give a compilation error, since all the objects added must have the same type as was declared, in this case, A.If you declare you
xcas, for instance:XClass<? extends AnInterface> xc = new XClass<AnInterface>();Then it’s not legal anymore to add
aorb, since the only thing we know is that xc is of some unknown but fixed subtype ofAnInterface, and there is no way to know if that unknown type isAorBor anything else.But let’s say you’re writing a method to accept a XClass type that you can iterate over the elements that were added before. Your only restriction (for the sake of the example), is that the items extend
AnInterface, you don’t care what the actual type is.You can declare this method like:
And now you can pass into this method anything like
XClass<A>,XClass<B>orXClass<AnInterface>, and it will all be valid.Keep in mind that you can’t add to the object you pass, for the same reason above. We don’t know what the unknown type is!