Converting Objects to Strings

As you learned in one of the earlier chapters, the Class Object implements a basic toString, which every class that inherits from Object will be able to use. The behavior in the Object class for the method just returns a String that is the name of the class, followed by the @ symbol, and a unsigned hexadecimal value of the hash code for the object.

You should most always override the toString method for your Java classes to provide a user-friendly String representation of the instance of the object. Listing 8.4 shows an example class that overrides the toString method to print out a more user-friendly representation of the instance.

Troubleshooting Tip

If you are not seeing the correct display string for one or more ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.