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

混江龙づ霸主 提交于 2019-12-05 04:26:18

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.

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

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

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