使用Java的@Override注释的最佳实践是什么?为什么?

用@Override注释标记每个被重写的方法似乎有点过分。是否有某些编程情况需要使用@Override,而其他情况不应该使用@Override?


当前回答

我认为它在编译时提醒大家,该方法的目的是重写父方法。举个例子:

protected boolean displaySensitiveInformation() {
  return false;
}

您将经常看到类似上述方法的内容,它覆盖基类中的方法。这是该类的一个重要实现细节——我们不希望显示敏感信息。

假设这个方法在父类中被更改为

protected boolean displaySensitiveInformation(Context context) {
  return true;
}

此更改不会导致任何编译时错误或警告-但它完全改变了子类的预期行为。

回答您的问题:如果在超类中缺少具有相同签名的方法,则表明存在错误,则应该使用@Override注释。

其他回答

仅用于方法声明。 指示带注释的方法 声明覆盖声明 在超类型。

如果持续使用,它可以保护您免受大量恶意漏洞的侵害。

使用@Override注释来避免这些错误: (在以下代码中发现错误:)

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());
    }
}

来源:Effective Java

最佳实践是始终使用它(或让IDE为您填充它们)

@Override有用性是检测父类中没有向下报告的变化。 如果没有@Override,你可以改变方法签名而忘记改变它的覆盖,使用@Override,编译器将为你捕获它。

有这样的安全网总是好的。

It seems that the wisdom here is changing. Today I installed IntelliJ IDEA 9 and noticed that its "missing @Override inspection" now catches not just implemented abstract methods, but implemented interface methods as well. In my employer's code base and in my own projects, I've long had the habit to only use @Override for the former -- implemented abstract methods. However, rethinking the habit, the merit of using the annotations in both cases becomes clear. Despite being more verbose, it does protect against the fragile base class problem (not as grave as C++-related examples) where the interface method name changes, orphaning the would-be implementing method in a derived class.

当然,这种情况多半是夸张的;派生类将不再编译,现在缺少重命名接口方法的实现,今天可能会使用重命名方法重构操作来处理整个代码库。

鉴于IDEA的检查无法配置为忽略已实现的接口方法,今天我将改变我的习惯和我的团队的代码审查标准。

我到处都用它。 关于标记方法的工作,我让Eclipse替我做,所以不需要额外的工作。

我对持续重构非常虔诚....所以,我会利用每一件小事让它进行得更顺利。

它所做的另一件事是,当读取代码时,它会更明显地改变父类的行为。这有助于调试。

此外,在Joshua Block的著作《Effective Java》(第二版)中,第36项详细介绍了注释的好处。