The Java library provides some annotations, but for many programmers, `@ Override``` is probably the most important. If you use
`@ Override``` consistently, bugs are less likely to occur.
Let's take a class that imitates the following bigram as an example (with a bug).
package tryAny.effectiveJava;
import java.util.HashSet;
import java.util.Set;
//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<>();
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());
}
}
I think this program will output 26, but it will output 260.
The cause is that I intend to override equals but have overloaded it. The argument of Object.equals
is of type Object and has a different signature.
To prevent such mistakes, add `` `@ Override``` to the method to override. Then the following code will result in a compilation error.
@Override public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
It should be as follows.
@Override
public boolean equals(Object o) {
if (!(o instanceof Bigram))
return false;
Bigram b = (Bigram) o;
return b.first == first && b.second == second;
}
For this reason, ** you should add @Override when overriding a method of the parent class **. There is one exception to this. In a concrete class, when overriding a parent abstract method, a compile error will occur unless it is overridden in the first place, so there is no need to write `` `@ Override``` (description). No harm due to).
Recommended Posts