@Override注释的目的是什么? [英] What is the purpose of the @Override annotation?

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

问题描述


可能重复:

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

我的问题是非常基本的,为什么我们人们使用 @Override 注释以及这个注释的重要性是什么?

My question is very basic why we people use @Override annotation and what is the importance of this annotation?

在旧JDK中为什么它不显示为警告,但在最新的JDK中它需要那么为什么..?

In Old JDK why it not show as warning, but in latest JDK it required then Why..?

推荐答案

假设你有:

public class Foo
{
    public void bar(String x, String y) {}
}

public class Foo2 extends Foo
{
    public void bar(String x, Object y) {}
}

真的意味着 Foo2.bar 覆盖 Foo.bar ,但由于签名错误,它没有。如果使用 @Override ,则可以让编译器检测到故障。它向任何读取指示这是覆盖现有方法或实现接口的代码 - 告知它们当前行为以及重命名方法可能产生的影响。

You really meant Foo2.bar to override Foo.bar, but due to a mistake in the signature, it doesn't. If you use @Override you can get the compiler to detect the fault. It also indicates to any reading the code that this is overriding an existing method or implementing an interface - advising them about current behaviour and the possible impact of renaming the method.

此外,如果方法覆盖方法指定 @Override ,这意味着您可以检测是否有人在没有您知道的情况下向超类添加了具有相同签名的方法 - 您可能不会希望覆盖新方法,因为您现有的方法可能有不同的语义。虽然 @Override 没有提供取消覆盖该方法的方法,但它至少突出了潜在的问题。

Additionally, your compiler may give you a warning if a method overrides a method without specifying @Override, which means you can detect if someone has added a method with the same signature to a superclass without you being aware of it - you may not want to be overriding the new method, as your existing method may have different semantics. While @Override doesn't provide a way of "un-overriding" the method, it at least highlights the potential problem.

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

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