views:

194

answers:

7

In Java, do class objects have the same heritance relations as the classes they represent?

+7  A: 

The .class property always returns a Class object. The Class class (weird) has a generic parameter. The generic parameter types are subclasses.

Class<String> stringClass = String.class;
Class<Object> objectClass = Object.class;

And because with generics, Type<foo> is NOT a supertype of Type<subtype_of_foo> (see the Java tutorials), this means, that the answer is "No".

Adam Paynter
No, generic parameter types are NOT subclasses; they're all the same class, due to type erasure, generic parameters don't exist once the compiler has done its thing.
Michael Borgwardt
Thanks for being able to put my thought into words. My brain isn't quite in gear. Time for some brain juice...
Adam Paynter
Class does carry it's generic argument...
Tom Hawtin - tackline
+4  A: 

Class objects in Java are all same Class.

You can tell because if you look at the Javadoc you can see that the Class class is final.

Dave Webb
+1  A: 

No, there is only one class with the name Class. String.class is an instanceof Class, as well as Object.class.

soulmerge
A: 

The reason Class does not extend Class even if Y extends X is that for any generic type G, G does not extend G

You might want to look this up in FAQ etc. A bag of apples is not a bag of fruit, even though apple is a fruit; because you can add any fruit to the latter but only apples to the former.

Hemal Pandya
+1  A: 

try this code:

boolean answer = Object.class.isAssignableFrom(String.class);
System.out.println(answer); // true!

however:

Class<Object> string = String.class; <-- compile-time error
Class<? extends Object> string = String.class; <-- it's ok
dfa
A: 

If I understand your question correctly, this is not the case. The object that represents class of java.lang.String, as well as any other class, is of class java.lang.Class always.

Bear in mind that java.lang.Class is defined as final, so you cannot subclass it.

pregzt
A: 

All Class objects are instances of a Class.

If you want to know the hierarchy of a class you can call the getSuperClass() and getInterfaces()

Note: you may need to call these recursively to get all super classes and interfaces.

Peter Lawrey