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

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

其他回答

接口实现上的@Override是不一致的,因为在java中没有“覆盖接口”这样的事情。

@Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway. There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.

在1.6中不应该允许接口实现@Override,而不幸的是,eclipse选择自动插入注释作为默认行为,我们得到了大量杂乱的源文件。在阅读1.6代码时,您无法从@Override注释中看出一个方法实际上覆盖了超类中的一个方法,还是仅仅实现了一个接口。

在重写超类中的方法时使用@Override是可以的。

每当一个方法覆盖了另一个方法,或者一个方法在接口中实现了签名。

@Override注释确保您确实重写了某些内容。如果没有注释,可能会出现拼写错误或参数类型和数字不同的情况。

当你使用Override时要小心,因为你不能在starUML之后做逆向工程;首先制作uml。

很简单——当您想重写父类中出现的方法时,使用@Override注释来进行正确的重写。如果你没有正确地覆盖它,编译器会警告你。

注释确实为编译器提供了关于代码的元数据,当我们重写基类的任何方法时,注释@Override用于继承的情况。它只是告诉编译器你正在重写方法。它可以避免一些常见的错误,如没有遵循正确的方法签名或在方法名称上出错等。所以使用@Override注释是一个很好的实践。