Reputation: 493
I know that when overriding equals()
and hashCode()
for an object in Java, you include the @Override
tag, but I can't seem to find any documentation stating that you should do the same when overriding toString()
--shouldn't it be the same since they are all inherited Object
methods?
Upvotes: 2
Views: 1179
Reputation: 300
You should annotate toString() with @Override, though legally there is no such requirement. The annotation @Override prevents the programmer from incorrectly overriding a superclass method; compile-time error occurs in case the override is incorrect.
The ideology is to detect errors as soon as possible after they are made, ideally at compile time.
Upvotes: 2
Reputation: 1069
Sure. It's never necessary to use the @Override
annotation, but it's helpful. From https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html:
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
Upvotes: 1
Reputation: 77234
You should always include the annotation whenever you're overriding a superclass method.
Upvotes: 3