什么是Java中的@Override? [英] What is @Override for in Java?

查看:198
本文介绍了什么是Java中的@Override?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

你什么时候使用Java的@Override注释?为什么?

是否有理由用 @Override 注释方法,而不是让编译器检查超类是否有该方法?

Is there any reason to annotate a method with @Override other than to have the compiler check that the superclass has that method?

推荐答案

如您所述,@ Override创建了一个编译时检查,表明正在覆盖某个方法。这对于确保在尝试覆盖时没有愚蠢的签名问题非常有用。

As you describe, @Override creates a compile-time check that a method is being overridden. This is very useful to make sure you do not have a silly signature issue when trying to override.

例如,我看到以下错误:

For example, I have seen the following error:

public class Foo {
  private String id;
  public boolean equals(Foo f) { return id.equals(f.id);}
}

此类编译为已编写,但将@Override标记添加到equals方法将导致编译错误,因为它不会覆盖Object上的equals方法。这是一个简单的错误,但它甚至可以逃脱经验丰富的开发人员的眼球

This class compiles as written, but adding the @Override tag to the equals method will cause a compilation error as it does not override the equals method on Object. This is a simple error, but it can escape the eye of even a seasoned developer

这篇关于什么是Java中的@Override?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆