使用Java的@Override注释的最佳实践是什么?为什么?
用@Override注释标记每个被重写的方法似乎有点过分。是否有某些编程情况需要使用@Override,而其他情况不应该使用@Override?
使用Java的@Override注释的最佳实践是什么?为什么?
用@Override注释标记每个被重写的方法似乎有点过分。是否有某些编程情况需要使用@Override,而其他情况不应该使用@Override?
当前回答
每次重写一个方法时使用它有两个好处。这样你就可以利用编译器检查来确保你实际上覆盖了一个方法。这样,如果您犯了拼写错误方法名或没有正确匹配参数的常见错误,您将得到警告,您的方法实际上并没有像您认为的那样重写。其次,它使您的代码更容易理解,因为当方法被覆盖时更明显。
此外,在Java 1.6中,您可以使用它来标记方法何时实现接口,以获得同样的好处。我认为最好有一个单独的注释(如@Implements),但总比没有强。
其他回答
它允许你(好吧,编译器)在你重写的方法名上使用了错误的拼写。
每当一个方法覆盖了另一个方法,或者一个方法在接口中实现了签名。
@Override注释确保您确实重写了某些内容。如果没有注释,可能会出现拼写错误或参数类型和数字不同的情况。
每次重写一个方法时使用它有两个好处。这样你就可以利用编译器检查来确保你实际上覆盖了一个方法。这样,如果您犯了拼写错误方法名或没有正确匹配参数的常见错误,您将得到警告,您的方法实际上并没有像您认为的那样重写。其次,它使您的代码更容易理解,因为当方法被覆盖时更明显。
此外,在Java 1.6中,您可以使用它来标记方法何时实现接口,以获得同样的好处。我认为最好有一个单独的注释(如@Implements),但总比没有强。
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的检查无法配置为忽略已实现的接口方法,今天我将改变我的习惯和我的团队的代码审查标准。
仅用于方法声明。 指示带注释的方法 声明覆盖声明 在超类型。
如果持续使用,它可以保护您免受大量恶意漏洞的侵害。
使用@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