Shubham Tyagi
Shubham Tyagi

Reputation: 191

Insight of toString method

Can you please explain what does the following line of code means

getClass().getName+"@"+Integer.toHexString(hashCode())

This is how toString() method is implemented in Object class but I cannot able to understand how it can call hashCode().

Upvotes: 0

Views: 418

Answers (2)

Julian
Julian

Reputation: 1675

Any instance of a class is allowed to invoke it's own methods by calling them directly. You could do this.getClass() or getClass() or this.hashCode() or hashCode().

getClass().getName() is the reflection (Reflection is a program's ability to inspect itself at runtime) way to get the name of the class from the running program. The result of that is then concatenated with the string "@" and the other string which is the hexadecimal string representation of the native hashCode() implementation.

Upvotes: 0

Joe.b
Joe.b

Reputation: 542

This returns a string consisting of 3 parts.

  1. the name of the class
  2. the '@' character
  3. the hash code of the object. hashCode() is another method of the Object class (and thus all other objects inherit it, since everything is a subclass of Object).

You can read more at the java api docs. https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

Upvotes: 1

Related Questions