何时在 Java 中使用 @Override [英] When to use @Override in java

查看:32
本文介绍了何时在 Java 中使用 @Override的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
什么时候使用Java的@Override注解,为什么?

来自 @Override 注释的 javadoc:

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.

我倾向于在测试中使用 @Override 注释,当我想测试一种类型的特定方法并替换我的测试对象调用的其他一些方法的行为时.我的一位同事坚信这不是有效用途,但不确定原因.谁能建议为什么要避免它?

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.

对于测试对象 Foo:

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

然后,如果我的 doExecute() 签名更改,我将在测试中收到编译错误,而不是令人困惑的执行失败.

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

推荐答案

在这类测试中使用 Override 注释是完全有效的,但该注释与测试完全没有特定关系;它也可以(并且应该)在整个生产代码中使用.

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.

这篇关于何时在 Java 中使用 @Override的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆