Override method with different signature

2020-04-04 10:20发布

问题:

I have a superclass with the method:

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.

回答1:

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.

From 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)

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
}

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

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).



回答2:

According to java overridding

The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

Here your method return type is different so it is not overridding.



回答3:

Reading the comments above, I understand that the approach wouldn't work, so I make some changes in the code and work like a charm, follows the code:

superclass:

protected VO processarRelatorioComEstado(Date dataInicial, Date dataFinal, Enum<?> estado) throws RelatorioException {

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

and the subclass:

public VO processarRelatorioComEstado(Date dataInicial, Date dataFinal, Enum<?> estado) throws RelatorioException {
//do something
return VOsubtype;

}

thanks guys.