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 Efficiency! Building the Model

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Why to @Override ???

Dear community,

I generally donΒ΄t understand why we should override methods?

In the Video Building the Model Craig uses this code:

@Override
public String to String() {
return String.format (Song %s by %s2", mTitle, mArtist);
}

What is the purpose of this code????

2 Answers

In Java, your classes automatically inherit a toString() method which attempts to print out a text representation corresponding to the object you have. However, not all the time does the output make sense. In many cases you might get something that looks like this:

test.myObject@18e2b22

The output is a unique hash code that corresponds to your object. Not very useful or descriptive, but this is the default toString() implementation. To make the information more useful you can Override the default implementation and use your own.

@Override
public String toString() {
    return String.format (Song %s by %s2", mTitle, mArtist);
}

The code above tells Java that first, we are overriding the toString() method in our class. Second, we then come up with a string output that is more descriptive than displaying a simple hash code. Our new toString() method makes it very easy to represent our current object as a string of text. Try renaming the toString() method to see how the default format looks.

Dylan Carter
Dylan Carter
4,780 Points

what is different about doing this than just making a new method that uses System.out.printf to print out the same thing?