开发者

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

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What's “@Override” there for in java? 开发者_如何学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


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;
    }
}


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜