Karel Bílek
Karel Bílek

Reputation: 37658

Java Class class as a generic doesn't work as expected

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

Answers (2)

Op De Cirkel
Op De Cirkel

Reputation: 29483

becauseClass<String> is not Class<Serializable>. However Class<String> is Class<? extends Serializable>

Upvotes: 3

Ernest Friedman-Hill
Ernest Friedman-Hill

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

Related Questions