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

Andrew D.
Andrew D.
2,937 Points

Without the @Override coded above the toString() method, would the constructor be called instead?

Hey guys! Just curious.. does the '@Override' make the compiler know that we want the toString() method called rather than our custom constructor when tweet is being instantiated?

1 Answer

JT Keller
JT Keller
12,731 Points

The toString and the class Constructor are two different things. The constructor instantiates or sets up the data for new objects that you create. These can be hard-coded or passed as arguments to the constructor. For example, if you created a car class and created a new instance of that car, you're constructor may start the car off having 4 tires, 1 windshield, 2 wipers, etc. What you would expect to be in a standard car. The toString method is inherited from the Object class. All classes even your custom classes inherit the based methods of the Object class (toString is one of these methods).

The @Override annotation lets other developers and the compiler know that you're overriding the inherited default toString method with something that more aptly meets your needs. @Override isn't necessary and simply lets the compiler know what your intention is.

As best practice, I would always stress using proper annotation so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

I hope this helps :)

Nana Baisie
Nana Baisie
8,535 Points

It certainly does. Thank you