Java generics to enforce return type of abstract method

前端 未结 5 1965
既然无缘
既然无缘 2020-12-17 18:59

I have the following situation :

abstract class X { abstract X someMethod (...) {...} }.

Now I want to constrain any implementation of X to

5条回答
  •  执念已碎
    2020-12-17 19:20

    Here's an approach that lets you return a parameter type for this:

    AbstractFoo> {
      /** Subclasses must implement to return {@code this}. */
      protected abstract T getThis();
    
      /**  Does something interesting and returns this Foo */
      public T inheritedThing {
        /* blah di blah */
        return getThis();
      }
    } 
    

提交回复
热议问题