Asdfasf

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?:

// Can you spot the bug?
public class Bigram {
private final char first;
private final char second;
public Bigram(char first, char second) {
this.first = first;
this.second = second;
}
public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
public int hashCode() {
return 31 * first + second;
}
public static void main(String[] args) {
Set<Bigram> s = new HashSet<Bigram>();
for (int i = 0; i < 10; i++)
for (char ch = 'a'; ch <= 'z'; ch++)
s.add(new Bigram(ch, ch));
System.out.println(s.size());
}
}


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: