Misnomer: The class named Class

So there’s a class named Class. But it represents interfaces, annotations and enums too. What’s up with that?

From the documentation:

Instances of the class Class represent classes and interfaces in a running Java application.

The method to get it is called getClass. But that makes sense as it returns an object representing the class (not an interface).

There’s also an interface¬†called Type. And in Java every class and interface define a type. This even represents raw types, parameterized types, array types, type variables and primitive types.

So why don’t they use Type instead of Class? Probably because they needed a type for a method called getClass and it seemed correct to use Class as its name.
Type actually exists as an interface, which Class implements. So you can always cast it to Type if you think it helps. And type is not reserved while class is. So that’s a better variable name too.

PS: Even the keyword void is represented as a Class.

Leave a Reply

Your email address will not be published. Required fields are marked *