使用高阶函数覆盖 java 中的抽象方法

Using higer order function to override abstract method in java

在摘要中class我有以下定义:

  protected abstract A expectedA(B b);

  protected Function<A, B> createExpectedA(Long foo) {
    return a -> { ... return b}}

然后我想用 createExpectedA 中的 return 函数覆盖抽象函数,如下所示:

  @Override
  protected Function<A, B> expectedA = createExpectedA(fee);

但是这给了我以下错误:

The annotation @Override is disallowed for this location

我怎样才能在 Java8 中做我想做的事?

注解 Override 用于方法而不是字段,这就是您收到此错误的原因。提醒一下,这是 Javadoc:

Indicates that a method declaration is intended to override a method declaration in a supertype. If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:

  • The method does override or implement a method declared in a supertype.
  • The method has a signature that is override-equivalent to that of any public method declared in Object.

你想做的好像是这样的:

@Override
protected A expectedA(B b) {
    return createExpectedA(fee).apply(b);
}