I tried to understand what is the reason for getClass
method to return Class extends |X|>
?
From the openjdk near public final
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()
.)