Java @Override 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4341432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:10:20  来源:igfitidea点击:

What does @Override mean?

javaannotationsoverriding

提问by Woong-Sup Jung

public class NaiveAlien extends Alien
{

    @Override
    public void harvest(){}

}

I was trying to understand my friend's code, and I do not get the syntax, @Override in the code. What does that do and why do we need in coding? Thanks.

我试图理解我朋友的代码,但我没有得到代码中的语法 @Override。那有什么作用,为什么我们需要编码?谢谢。

采纳答案by EboMike

It's a hint for the compiler to let it know that you're overriding the method of a parent class (or interface in Java 6).

这是一个提示,让编译器知道您正在覆盖父类(或 Java 6 中的接口)的方法。

If the compiler detects that there IS no function to override, it will warn you (or error).

如果编译器检测到没有要覆盖的函数,它会警告您(或错误)。

This is extremely useful to quickly identify typos or API changes. Say you're trying to override your parent class' method harvest()but spell it harvset(), your program will silently call the base class, and without @Override, you wouldn't have any warning about that.

这对于快速识别拼写错误或 API 更改非常有用。假设您试图覆盖父类的方法harvest()但拼写它harvset(),您的程序将默默地调用基类,如果没有@Override,您将不会收到任何警告。

Likewise, if you're using a library, and in version 2 of the library, harvest()has been modified to take an integer parameter, you would no longer override it. Again, @Overridewould quickly tell you.

同样,如果您使用的是库,并且在库的第 2 版harvest()中已修改为采用整数参数,则您将不再覆盖它。再次,@Override会很快告诉你。

回答by fastcodejava

@Overridemeans you are overriding the base class method. In java6, it also mean you are implementing a method from an interface. It protects you from typos when you think are overriding a method but you mistyped something.

@Override意味着您正在覆盖基类方法。在 java6 中,这也意味着您正在从接口实现一个方法。当您认为要覆盖一个方法但您输入错误时,它可以保护您免受拼写错误的影响。

回答by nitin1706

This feature is called an annotation. @Overrideis the syntax of using an annotation to let the compiler know, "hey compiler, I'm changing what harvest does in the parent class", then the compiler can immediately say, "dude, you are naming it incorrectly". The compiler won't compile until you name it correctly.

此功能称为注释。@Override是使用注解让编译器知道的语法,“嘿编译器,我正在改变收获在父类中的作用”,然后编译器可以立即说,“伙计,你命名不正确”。除非您正确命名,否则编译器不会编译。

So, without this @Overrideannotation, the compiler won't error and it will be considered a new method declaration. It would be difficult to recognize the error at this point.

所以,如果没有这个@Override注解,编译器就不会出错,它会被认为是一个新的方法声明。此时很难识别错误。