Item 40: Consistently use the Override annotation

40. Use Override annotations consistently

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

Item 40: Consistently use the Override annotation
Item 59: Know and use the libraries
Item 44: Favor the use of standard functional interfaces
Item 52: Use overloading judiciously
Item 53: Use varargs judiciously
Item 45: Use streams judiciously
Item 83: Use lazy initialization judiciously
Item 66: Use native methods judiciously
Item 26: Don't use raw types
Why you should add the Override annotation when overriding a method