Java. getClass() returns a class, how come I can get a string too?

System.out.println(someobj) is always equivalent to:

System.out.println(String.valueOf(someobj));

And, for non-null values of someobj, that prints someobj.toString();

In your case, you are doing println(obj.getClass()) so you are really doing:

System.out.println(String.valueOf(obj.getClass()));

which is calling the toString method on the class.


All objects in Java inherit from the class Object. If you look at that document, you'll see that Object specifies a toString method which converts the object into a String. Since all non-primitive types (including Classes) are Objects, anything can be converted into a string using its toString method.

Classes can override this method to provide their own way of being turned into a string. For example, the String class overrides Object.toString to return itself. Class overrides it to return the name of the class. This lets you specify how you want your object to be output.

Tags:

Java