When to use @Override in java [duplicate]

2019-07-26 16:25发布

问题:

Possible Duplicate:
When do you use Java’s @Override annotation and why?

From the javadoc for the @Override annotation:

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.

I've tended to use the @Override annotation in testing, when I want to test a specific method of a type and replace the behaviour of some other method called by my test subject. One of my colleagues is firmly of the opinion that this is not a valid use but is not sure why. Can anyone suggest why it is to be avoided?

I've added an example below to illustrate my usage.

For the test subject Foo:

public class Foo {
    /**
     * params set elsewhere
     */
    private Map<String, String> params;

    public String doExecute(Map<String, String> params) {
        // TODO Auto-generated method stub
        return null;
    }

    public String execute() {
        return doExecute(params);
    }
}

I would define a test like this:

public void testDoExecute() {
    final Map<String, String> expectedParams = new HashMap<String, String>();
    final String expectedResult= "expectedResult";
    Foo foo = new Foo() {
        @Override
        public String doExecute(Map<String, String> params) {
            assertEquals(expectedParams, params);
            return expectedResult;
        }
    };

    assertEquals(expectedResult, foo.execute());
}

Then if my doExecute() signature changes I'll get a compile error on my test, rather than a confusing execution failure.

回答1:

Using the Override annotation in that kind of tests is perfectly valid, but the annotation has no specific relationship to testing at all; It can (and should) be used all over production code as well.



回答2:

The purpose of @Override is that you declare your intent to override a method, so that if you make a mistake (e.g. wrong spelling of the method name, wrong argument type) the compiler can complain and you find your mistake early.

So this is a perfectly valid use.



回答3:

Compile with -Xlint on. It will complain about missing @Override's or @Overrides in the wrong place.



回答4:

@Override ensures that you in fact override the method rather than accidentally overload it, and the compiler warning helps you determine if you overrode a method you intended to overload.

Using it in this case is perfectly legitimate, but given that it is a test, the test should fail if you overload the method instead of overriding it (say change the method signature), so perhaps it isn't important in this case.