博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective Java 36 Consistently use the Override annotation
阅读量:5008 次
发布时间:2019-06-12

本文共 1953 字,大约阅读时间需要 6 分钟。

Principle

Use the Override annotation on every method declaration that you believe to override a superclass declaration.

 

// 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;

}

// This method is not the equals(Object) 's override, it's just a new method

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()); // it will print 260 not 26.

}

}

 

The @Override annotation will help you find the issue at the compile time.

Bigram.java:10: method does not override or implement a method

from a supertype

@Override public boolean equals(Bigram b) {

^

// The correct overriding

@Override public boolean equals(Object o) {

if (!(o instanceof Bigram))

return false;

Bigram b = (Bigram) o;

return b.first == first && b.second == second;

}

   

Note

It is worth annotating all methods that you believe to override superclass or super interface methods, whether concrete or abstract. For example, the Set interface adds no new methods to the Collection interface, so it should include Override annotations on all of its method declarations, to ensure that it does not accidentally add any new methods to the Collection interface.

   

Summary

The compiler can protect you from a great many errors if you use the Override annotation on every method declaration that you believe to override a supertype declaration, with one exception. In concrete classes, you need not annotate methods that you believe to override abstract method declarations(though it is not harmful to do so).

   

转载于:https://www.cnblogs.com/haokaibo/p/Consistently-use-the-Override-annotation.html

你可能感兴趣的文章
C++复习:对C的拓展
查看>>
C# DevExpress TreeList指定KeyFieldName后无法显示该列的问题
查看>>
多条记录的同一字段组合成一个字符串 FOR XML PATH
查看>>
APUE学习笔记——10.9 信号发送函数kill、 raise、alarm、pause
查看>>
剑指Offer面试题33(java版):把数组排成最小的数
查看>>
jquery中的 $(function(){ .. }) 函数
查看>>
奇怪的国家
查看>>
Linux nohup命令详解
查看>>
[MSDN] Using the Windows Azure Storage Services
查看>>
计算回文数
查看>>
校外实习报告(九)
查看>>
android之android.intent.category.DEFAULT的用途和使用
查看>>
CAGradientLayer 透明渐变注意地方(原创)
查看>>
【OpenSource】--Web Bench 1.5
查看>>
python-1:工欲善其事,必先利其器 安装配置Anaconda x32位 更新后,启动不了,解决方案(亲测)...
查看>>
Linux 命令(二) Linux下查看文件文件内容命令
查看>>
ubuntu系统如何屏幕截图
查看>>
ArcGIS Engine 创建索引(属性索引)——提高查询效率
查看>>
栅格数据AE
查看>>
开发笔记
查看>>