微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 具有不同签名的覆盖方法

我有一个超类使用该方法
protected <E extends Enum<E>,T extends VO> void processarRelatorioComEstado(Date dataInicial,Date dataFinal,E estado) throws RelatorioException {

    throw new UnsupportedOperationException("method not overridden");
}

在其中一个子类中,我想要执行以下操作:

@Override
protected <E extends Enum<E>> DemonstrativoReceitaDespesasAnexo12Vo processarRelatorioComEstado(Date dataInicial,E estado) throws RelatorioException {
//do something
return DemonstrativoReceitaDespesasAnexo12Vo;
}

但这只是行不通.问题是我有一个超类的引用,我想调用这个方法,但只能在其中一个子类中调用.

解决方法

您无法在重写方法中更改类型参数的数量.至于你的情况,覆盖明显失败,返回类型.但即使返回类型相同,您的方法仍然不会覆盖等效,因为您在所谓的重写方法中具有较少的类型参数.

JLS – Method Signature开始:

Two methods have the same signature if they have the same name and
argument types.

Two method or constructor declarations M and N have the same argument
types if all of the following conditions hold:

  • They have the same number of formal parameters (possibly zero)
  • They have the same number of type parameters (possibly zero)

因此,即使以下代码也会失败:

interface Demo {
    public <S,T> void show();
}

class DemoImpl implements Demo {
    @Override
    public <T> void show() { }  // Compiler error
}

由于类型参数较少,因此类中的方法show()不会与接口中的方法等效.

因此,您应该确保方法签名与JLS部分中指定的完全相同(相同名称,相同数量和类型的参数(包括类型参数),共变量返回类型).

原文地址:https://www.jb51.cc/java/129183.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐