@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 $ c $,则编译器可能会发出警告c>,这意味着您可以检测是否有人在没有您知道的情况下向超类添加了具有相同签名的方法 - 您可能不会希望覆盖新方法,因为您现有的方法可能有不同的语义。虽然
@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.