可选返回类型:尝试使用不兼容的返回类型

Bou*_*n_7 -1 java generics

错误:

'get()' in 'test.B' clashes with 'get()' in 'test.A'; attempting to use incompatible return type
Run Code Online (Sandbox Code Playgroud)

代码如下,请问如何解决?谢谢!

'get()' in 'test.B' clashes with 'get()' in 'test.A'; attempting to use incompatible return type
Run Code Online (Sandbox Code Playgroud)

Cha*_*ire 5

您需要泛化A泛型参数并将其绑定为 的子类A

interface A<S extends A<S>> {

  Optional<S> get() ;
}
Run Code Online (Sandbox Code Playgroud)

现在B声明返回可选的B

interface B extends A<B> {

  @Override
  Optional<B> get();
}
Run Code Online (Sandbox Code Playgroud)

请注意,重写get()是多余的,因为B extends A<B>该方法已经返回Optional<B>

请记住,这不会阻止您使用 a C,它返回一个可选的B

interface C extends A<B> {

  @Override
  Optional<B> get();
}
Run Code Online (Sandbox Code Playgroud)