Reputation: 37658
A simple question about Class and its generic semantics. Why doesn't the following code work?
Class<Serializable> s = String.class;
Java tells me that Class<Serializable>
and Class<String>
are incompatible. How can they be, when String
is implementing Serializable
?
Shouldn't generics allow exactly this type of things?
Upvotes: 0
Views: 90
Reputation: 29483
becauseClass<String>
is not Class<Serializable>
. However Class<String>
is Class<? extends Serializable>
Upvotes: 3
Reputation: 81694
No, generics explicitly don't allow this kind of thing. The classic example is a collection class of some kind. If ArrayList<String>
was a subclass of ArrayList<Serializable>
, then you could write
ArrayList<String> astr = new ArrayList<String>();
ArrayList<Serializable> aser = astr;
aser.add(new Integer());
// This will throw ClassCastException!
String str = astr.get(0);
After this code, you have an ArrayList<String>() containing an Integer
object -- clearly this is not good.
Upvotes: 3