Java generics to enforce return type of abstract method

前端 未结 5 1962
既然无缘
既然无缘 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:16

    This should work just fine:

    class X<T> {
      abstract T someMethod(...);
    }
    
    class X1<T1> extends X
      T1 someMethod(...) {
        ...
      }
    }
    
    0 讨论(0)
  • 2020-12-17 19:19

    Yes. This is return type covariance.

    0 讨论(0)
  • 2020-12-17 19:20

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

    AbstractFoo<T extends AbstractFoo<T>> {
      /** 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();
      }
    } 
    
    0 讨论(0)
  • 2020-12-17 19:22

    This works as well;

    abstract class X<T> {
        public abstract T yourMethod();
    }
    class X1 extends X<X1> {
        public X1 yourMethod() {
            return this;
        }
    }
    class X2 extends X<X2> {
        public X2 yourMethod() {
            return this;
        }
    }
    
    0 讨论(0)
  • 2020-12-17 19:33
    abstract class X<I extends X<I>> {
        protected X(Class<I> implClazz) {
            if (!getClass().equals(implClazz)) {
                throw new IllegalArgumentException();
            }
        }
    
        abstract I someMethod();
    }
    

    Rationale: You can not refer to the dynamic type in type bounds, hence the indirect check in the constructor.

    0 讨论(0)
提交回复
热议问题