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 Getting There Object Inheritance

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

toString method !

Hey folks,

i still don´t get the whole toString concept.

Inside our Treet class we write a new toString method that is different from the toString method of the super class Object right .

In our test class we instantiate a new object of the Treet class and call a print method and paste an treet object as argument.

System.out.println("This is a new Treet : " + treet);

Before we overriden the toString method the treet was "com.teamtreehouse.Treet@511d50c0" and now I am getting a String representation of this object right?

But how the compiler knows that I want a String representation of the object and not something else ???

I hope you understand my english ...

CONFUSION !!!

2 Answers

Seth Kroger
Seth Kroger
56,413 Points

Since you're using string concatenation in the form of "string" + ... the compiler knows all the pieces need to be strings and will call toString() on anything that isn't. This is one of the very few times Java will do an implicit type conversion.

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Good morning Seth,

thank you for a quick reply.

I have two questions left :)

So if I try to concatenate Strings somewhere in any method, tho compiler calls toString. If the toString method isn´t overriden yet, nothing happens and I get an object like tweet? Or if toString is overriden, I get what I have done inside toString?

Implicit type conversation means object into String?

Grigorij

Evgeny Chulak
Evgeny Chulak
906 Points

If you haven't overridden the toString() method, something still happens but it will not necessarily perform what you want. It will simply use toString() of the Object class which prints out the memory location of the desired object. Once you define how you want your object to be printed by overriding the toString() method, it will perform the operation you have defined in your new toString() method.

Is this the reason that we are getting "com.teamtreehouse.Treet@511d50c0" as output in the "Class Review" video, because we have not overridden the toString() method?

Seth Kroger
Seth Kroger
56,413 Points

Yes, the default toString() method for Object is the full class name and the object's hashCode() in hexadecimal.