views:

277

answers:

3

Suppose the following object structure:

class Super {}

class SubA extends Super {}
class SubB extends Super {}

I want to be able to have a variable that will hold the class object for either of my subclasses. I feel like this should do it:

Class<Super> classObj;

Then, I want to be able to something like this:

classObj = SubA.class;

or:

classObj = SubB.class;

This doesn't work though. I get the following error:

Type mismatch: cannot convert from Class<SubA> to Class<Super>

Any ideas why? What do I need to fix?

+11  A: 

You need a bounded wildcard:

Class<? extends Super> classObj;

See the lesson on wildcards from the Java tutorials.

Michael Myers
+1  A: 

As mmyers pointed out you could use wildcarding.

As an alternative, you could have the classes implement a common interface and then access them through that interface.

kgrad
Number 17!
Michael Myers
I don't follow?
kgrad
Don't mind me; I just keep a (rough) running total of people who misspell my name. I only started a month ago and I'm up to 17 already. And one of them is Jeff Atwood--I'm practically almost sort of famous!
Michael Myers
Ah, my apologies, the situation has been rectified.
kgrad
No problem; I'm used to it by now. (My brother once got a letter which was addressed to him, except that they misspelled all three of his names. He eventually got over it.)
Michael Myers
+1  A: 

Try this (fails to compile):

public class ListCopy {
  public static void main(String[] args) {
    List<String> stringList = new ArrayList<String>();
    List<Object> objectList = stringList;
  }
}

This will fail to compile even though String extends Object. Java stuff is not covariant - type parameters are erased, so the compiler does not know what will be there at runtime.

It's the same with Class.

George