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

Bradley Stone
Bradley Stone
933 Points

toString() confusion

I'm a little confused as to why the program outputs the revised format after adding in

public String toString() { return "Treet: \"" + mDescription + "\" - @" + mAuthor; }

Could someone please explain step by step as to why the output is changed after adding in the toString() method? I know I'm missing something critical about inheritance here.

Simon Coates
Simon Coates
28,694 Points

subclasses can create methods with signatures that match methods on classes from which they inherit. When code tries to call the method, it finds the subclass method.

1 Answer

Yeah, but it wasn't explained that apparently the printf() in the main() calls the toString() and that is how ("%s", treet) gets substituted with the overridden toString() method from the Treet class.