Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Efficiency! Building the Model

Nathan Quirk
Nathan Quirk
3,679 Points

Why @override the .toString method instead of creating a new one?

I understand what Craig is doing here with the @Override statement - overriding the normal behavior of the .toString method inherited from the parent class to mean something different. But - WHY? Why not create a new method by a new name and call it something else?

1 Answer

andren
andren
28,558 Points

Let me turn the question around, why wouldn't he override the toString method if he wants a method that converts the object to a string. When that is the precise purpose of the toString method? Not overriding the method wouldn't offer any benefits and it would go against the expected behavior since a class' toString method is supposed to be overridden. That is the recommended action to take with that method.

Beyond that it's also worth noting that since it is expected that most classes have overridden their toString method and it is guaranteed to exist on all objects regardless it's very common for this method to be called automatically when some method tries to display an object as a string.

If you pass an object to a print statement for example it will automatically print the string form of the object even if you don't call the toString method on your own. This is because it will pass the object into String.valueOf which in turn more or less just calls the object's toString method.