问题描述
我的方法具有超类:
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-方法签名:
两个方法或构造函数声明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).
这篇关于具有不同签名的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!