Background
If you create a new class and do not override the toString
method
then, by default, you will get Object.toString. This returns the following:
getClass().getName() + '@' + Integer.toHexString(hashCode())
The javadoc recommends that all subclasses should override the toString.
Tips
-
Use the
@Override
annotation above the method signature to ensure it is correct. -
NEVER EVER print! Your
toString
method should return theString
representation of your class. -
Always document what format you are using in your comments/javadoc.
-
If your class provides a
toString
method, also provideGetters
so that programmers using your class have a way to access the data used to create yourtoString
method.
The user should never have to parse yourtoString
method to obtain information. -
Consider using
String.format()
to enhance the flexibility and readability of your code.