0

I've read this question but I'm not fully satisfied by it. Here is my code:

public static void main(String args[]){
   Car c = new Car();
   System.out.println(c);
   System.out.println(c.getClass());
}

Output:

Car@xxx
Car

And I have not understood why in the first case it prints also the hashCode and it does not in the second. I've seen how println(Object obj) is defined and the methods it uses, and they are the same, in fact, at the deepest level of stack calls, toString() is defined like this:

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

So why at the output I can't see "@xxx"?
Thank you in advance.

AlessandroF
  • 542
  • 5
  • 16
  • 3
    Because `c.getClass()` returns a `Class>` object, and the class `Class` overrides the `toString` method so that `Class.toString` doesn't do the same thing as `Object.toString`. If it did, you'd see `Class@xxx` instead of `Car@xxx`. – kaya3 Jan 27 '20 at 22:14
  • Thank you guys. The doubt came to me because I did Ctrl+click on println from Eclipse, and it brought me on the method which receives an Object, not a Class. Does it mean that's an error of Eclipse? – AlessandroF Jan 27 '20 at 22:27
  • 1
    The error is not in Eclipse, but in your expectations. The behavior is correct. (The class `Class` overrides the `toString` implementation you have quoted.) – Louis Wasserman Jan 27 '20 at 23:23

3 Answers3

3

Because getClass() will return the instance of Class

public final Class<?> getClass()

And when you print Class instance, toString is called which returns the name, here is the toString implementation of Class in java

public String toString() {
    return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
        + getName();
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

Class.toString is defined differently, exactly generating the output you see. It's just printing the class' name. There's no Object.toString default in that class ever invoked

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
1

In the following statement, toString() method of Car is called:

System.out.println(c);

In the following statement, toString() method of Class is called:

System.out.println(c.getClass());

Since you haven't overridden the toString() method of Car, the toString() method of Object is getting called giving you output like Car@xxx.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110