简体   繁体   中英

Java Generics - Cannot override a method with an extends generic

I have this method in a service AbstractClass:

public <E extends EntityFilter> Specification<T> getSpecifications(E entityFilter) {
    return null;
}

Then I have an implementation for EntityFilter too:

public class UserEvaluationFilter implements EntityFilter {
    @Getter
    @Setter
    private String evaluator;
}

And I want to override the AbstractClass in my serviceClass (which extends the controller AbstractClass) method like this:

@Override
public Specification<UserEvaluation> getSpecifications(UserEvaluationFilter filter) {
    return doStuff();
}

The compiler says that this is not overriding any method of my AbstractClass.

What's wrong?

The method signature you have declared in the abstrct class says that the method should accept any subclass of EntityFilter as that parameter.

Actually, the type variable is redundant there: you may as well just declare it as:

public Specification<T> getSpecification(EntityFilter entityFilter)

What you're trying to do in your subclasses is to make the parameter type more specific than EntityFilter ; but this is forbidden by the Liskov Subtitution Principle , which says that subclasses must be:

  • No more specific in the parameters they accept;
  • No more general in the values they return.

As such, the method you are trying to declare in the subclass doesn't actually override the method in the supertype, so it is forbidden.

To deal with this, you need to make the filter type a class-level type variable:

class AbstractClass<T, E extends EntityFilter> {
  public Specification<T> getSpecifications(E entityFilter) {
    return null;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM