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

后端 未结 4 1408
广开言路
广开言路 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:37

    As you probably know, every class in Java inherits from the Object class. This means that every class automatically has the method toString(), which returns a representation of the object as a String. When you concatenate a string with an object, or if you pass an Object into an argument where there should be a String, Java automatically calls the toString() method to convert it into a String. In your case, the toString() method has been overridden to return the name of the class.

    You can see this happen with other objects, too:

    Set s = new Set();
    s.add(1);
    s.add(3);
    s.add(5);
    System.out.println(s);
    

    will output "[1, 3, 5]".

提交回复
热议问题