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 trialNhat Anh Dao
8,370 PointsSomebody please explain the benefit of using @Override
We already have a toString method in the Song class
@Override
public String toString() {
printf("song %s by %s", getSong, getArtist);
}
But why in the main method, we just do this
System.out.printf("Add %s %n", song);
Instead of
System.out.printf("Add %s %n", song.toString);
Did @Override do something with it?
1 Answer
Gavin Ralston
28,770 PointsThe Override annotation is there so you're aware that you're overriding a method from a parent class or interface.
In fact, you can do away with the @Override annotation and it'll work exactly the same, it's just easier to see when you put the notation on. Any time you write a method which has the same signature (name, return type, parameters are all the same) it'll Override (or over write, if that's easier) the original method it was passed down.
You could call toString() explicitly, but in the printf() method, you're always going to get the object's toString method anyway, if it's not already a string.
So the second argument you pass in is a song, and printf() is going to be like "Okay this isn't a string...so I'll call its toString() method to plug in here"
That toString() method is available in every single object in Java, but you had to Override it in order for the response to be meaningful (say, a song title and artist) instead of just returning a string representation of its address in memory.
Nhat Anh Dao
8,370 PointsNhat Anh Dao
8,370 PointsThank you, that's help :) I understand it now