6

I tried to understand what is the reason for getClass method to return Class<? extends |X|>?

From the openjdk near public final native Class<?> getClass();:

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.

Why can't getClass have the same type such as XClass.class, for example:

class Foo {}
Foo fooInstance = new Foo();
Class<Foo> fc = Foo.class; // Works!
Class<Foo> fc2 = fooInstance.getClass(); // Type mismatch ;(
Class<?> fc3 = fooInstance.getClass(); // Works!
Class<? extends Foo> fc4 = fooInstance.getClass(); // Works!
Tunaki
  • 116,530
  • 39
  • 281
  • 370
Aviel Fedida
  • 3,702
  • 9
  • 48
  • 81
  • Related: http://stackoverflow.com/questions/19332856/what-is-meant-by-the-erasure-of-the-static-type-of-the-expression-on-which-it-i and http://stackoverflow.com/questions/18144556/java-getclass-of-bounded-type – Tunaki Jun 13 '16 at 18:34

1 Answers1

8
Foo foo = new SubFoo();

What do you expect foo.getClass() to return? (It's going to return SubFoo.class.)

That's part of the whole point: that getClass() returns the class of the real object, not the reference type. Otherwise, you could just write the reference type, and foo.getClass() would never be any different from Foo.class, so you'd just write the second one anyway.

(Note, by the way, that getClass() actually has its own special treatment in the type system, not like any other method, because SubFoo.getClass() does not return a subtype of Foo.getClass().)

Louis Wasserman
  • 172,699
  • 23
  • 307
  • 375