In Java, do class objects have the same heritance relations as the classes they represent?
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".
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
.
No, there is only one class with the name Class
. String.class is an instanceof Class, as well as Object.class.
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.
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
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.
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.