AlessandroF
AlessandroF

Reputation: 562

System.out.println prints different Strings on the same Object type using getClass()

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.

Upvotes: 0

Views: 65

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

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.

Upvotes: 1

Olaf Kock
Olaf Kock

Reputation: 48057

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

Upvotes: 1

Ryuzaki L
Ryuzaki L

Reputation: 40048

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();
}

Upvotes: 3

Related Questions