具有不同签名的替代方法 [英] Override method with different signature

查看:170
本文介绍了具有不同签名的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法具有超类:

protected <E extends Enum<E>,T extends VO> void processarRelatorioComEstado(Date dataInicial, Date dataFinal, E estado) throws RelatorioException {

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

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

and in one of its subclasses I want to do the following:

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

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

but this just doesn't work. The problem is that I have a reference to a superclass, and I want to call this method, but only in one of the subclasses.

推荐答案

您不能在重写方法中更改类型参数的数量.对于您的情况,返回类型显然会覆盖失败.但是,即使返回类型相同,您的方法仍然不会被覆盖等效,因为您应该覆盖的方法中的类型参数更少.

You can't change the number of type parameters in the overridden method. As for your case, override clearly fails with the return type. But even if the return types were same, your method still wouldn't be override equivalent, as you have fewer type parameters in the supposed-to-be overridden method.

来自 JLS-方法签名:

如果两个方法具有相同的名称和名称,则它们具有相同的签名. 参数类型.

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

两个方法或构造函数声明M和N具有相同的参数 键入是否满足以下所有条件:

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)

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

So, even the following code would fail:

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

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

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

As the method show() in class is not override equivalent with the method in interface, due to fewer type parameters.

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

So, you should make sure that the method signature is exactly the same, as specified in that JLS section (Same name, same number and type of parameters (including type parameters), co-variant return type).

这篇关于具有不同签名的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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