Java - what is “@Override” used for? [duplicate]

廉价感情. 提交于 2019-12-10 04:15:02

问题


Possible Duplicate:
What's “@Override” there for in java?

I've never put "@Override" before a method until now. I see some code examples with it, but I don't understand its utility. I'd love some explanation.

Many thanks,

JDelage


回答1:


First, you can't annotate a class with @Override. This annotation indicates that a method declaration is intended to override a method declaration in a superclass.

You don't have to annotate overriding methods but if you use this annotation and your annotated method does not override a superclass method, then the compiler will generate an error message.




回答2:


Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

http://download.oracle.com/javase/6/docs/api/java/lang/Override.html

The case I like to explain its use is when overriding equals.

This will error because equals expects an Object parameter:

public class Foo{

    @Override
    public boolean equals(Foo f){
        return true;
    }
}



回答3:


The best example - overriding equals().

If you write a class like this:

public class Foo 
{
    public String bar;

    public boolean equals(Foo other)
    {
        return this.bar.equals(other.bar);
    }
}

then you've overloaded the equals method, rather than overriding Object.equals as was intended.

If you annotate the equals method with @Override, the compiler will give you an error stating (correctly) that you haven't overridden a superclass method.

In Java 6, you can use this for implementing interface methods too - this is handy when you're only adding a method to your class to satisfy some interface, and hence the compiler can check that it's required and alert you to the interface changing.

As with all annotations it's effectively a programmatic comment, but having the compiler check that your assumptions are (still) correct is very handy in these cases.




回答4:


It's there to express that you expect the method to be overriding a superclass method. It does come in handy when you make a mistake spelling the method name or give it the wrong parameters so that it does not override what you thought it was overriding.




回答5:


It's a conventional comment. Some compilers make sure that the function followed by @Override is actually an override... just a failsafe



来源:https://stackoverflow.com/questions/4185397/java-what-is-override-used-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!