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

后端 未结 4 1438
广开言路
广开言路 2021-01-02 00:58

When I use System.out.println(obj.getClass()) it doesn\'t give me any error. From what I understand getClass() returns a Class type. Since p

4条回答
  •  佛祖请我去吃肉
    2021-01-02 01:25

    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.

提交回复
热议问题