Sunday, August 24, 2014

EJ-36 Consistently Use the Override Annotation

This is the case I meet frequently, thanks to Eclipse, it puts automatically when a class implements an interface or extends a super class.

Ref: Effective Java by Joshua Bloch

Can you spot the bug?:

The program tries to utilize equals method of Object by intention of overriding equals method, but it can not, since to override Object.equals, you must define an equals method whose parameter is of type Object. 

Luckily, the compiler can help you find this error, but only if you help the compiler by telling it that you intend to override Object.equals. To do this, annotate Bigram.equals with @Override as shown below

@Override public boolean equals(Bigram b) {
      return b.first == first && b.second == second;

Therefore, you should use the Override annotation on every method decleration that you believe to override a superclass decleration.

No comments: