Search code examples
javaobjectgenericswildcardreturn-type

Return type of get Class method is different from actual returntype


When I created a instance of a class A and tried to access its getClass() method, its return type is different than what is mentioned in java Object class.

A a = new A() ;
Class<? extends A> clazz = a.getClass();

Even when I access the getClass method as mentioned above in Intellij, it says its return type is Class<? extends A> and even the java doc says it returns wildcard extends upper bound. I can totally accept it. Because I can create instance of B and reference to A and access getClass method.

But why does the return type of the getClass method is justClass<?> in the Object class

Edit 1 (After the comment from Andy Turner)

Class A {
   List<?> returningNullList() {
     return null;
   } 
} 

When I create a instance of A , and tried to access returningNullList () method, it didn't give me return type as List<? extends A>. But when I tried to access getClass method it says return type is Class<? extends A> although the actual hard-coded return type is Class<? > in Object.java file

Is the getClass method is treated specially by compiler?


Solution

  • Read the documentation, i.e. the javadoc of getClass() in class Object:

    The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

    Number n = 0;
    Class<? extends Number> c = n.getClass();
    

    The bolding is from the javadoc, not added by me.

    For class Object itself, it means that the return type is Class<? extends Object>, but since Class<?> is shorthand for Class<? extends Object>, the javadoc simply shows the shorthand.

    Quoting the Java Language Specification, section 4.5.1. Type Arguments of Parameterized Types:

    The wildcard ? extends Object is equivalent to the unbounded wildcard ?.