Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Efficiency! Menu UI

Brent Mayberry
Brent Mayberry
1,029 Points

How does promptNewSong() in KaraokeMachine.java know to use the override for toString()?

In this code block:

private Song promptNewSong() throws IOException {
    System.out.print("Enter the artist's name:  ");
    String artist = mReader.readLine();
    System.out.print("Enter the title:  ");
    String title = mReader.readLine();
    System.out.print("Enter the video URL:  ");
    String videoURL =  mReader.readLine();
    return new Song(artist, title, videoURL);

  }

When this private method returns the Song object, how does the override to toString() get called so that the input is formatted the way we specified earlier if we don't explicitly call toString()? Does it have something to do with the nature of toString()?

Thanks in advance. I appreciate your help.

1 Answer

Enrique Munguía
Enrique Munguía
14,311 Points

I quite don't understand your question, so I will elaborate on the way toString() works. This method is inherited by every class from the Object class, when you override it you can specify any string to represent your instance in a printed form. One peculiarity of toString() is that it will be called implicitly when you print an instance of an object:

CustomObject obj = new CustomObject();
System.out.println(obj); // prints the String representation provided by toString()

Is equivalent to this

CustomObject obj = new CustomObject();
System.out.println(obj.toString()); // here we are calling toString() explicitly

For the purpose of this example I use CustomObject class, but in fact it could be an instance of any class, and this will work.

Brent Mayberry
Brent Mayberry
1,029 Points

This answers my question. I must have missed the memo that toString() is inherited by every class and that it is implicitly called whenever you print an instance of an object.

Thanks for taking the time to explain this. It seemed like "magic" that the output was formatted the way we had overridden the toString() method. Now I get how this happens.