When and why use Java @Override annotation
When should we use @Override
annotation
- When you want to override a method of parent class
- When you want to implement a method of an interface
And if we forgot to use @Override
annotation
It’s just fine, no error happens. But there will be potential unexpected behaviours due to human mistakes.
So why should we use @Override
annotation
- For code readability.
- To take advantage of compiler error checking.
- If Parent class changed, we can immediately see error when compiling.
Check this example: suppose we have a class Vehicle:
This is case when we don’t use @Override
annotation:
This code is wrong: we intend to override method hello
, but we misspelling it, into halo
. There is no error at
compile time, but only when run time. Let’s run a test to confirm:
This type of error is bad, because it leaves potential bug, until late phase like test or even worse, production
phase. The best practice is to avoid it, by using @Override
annotation, let’s rewrite the code:
The error can be detected asap, at compile time!
So it’s best practice to use @Override
annotation whenever:
- You want to override a method of parent class
- You want to implement a method of an interface