Java generics - overriding an abstract method and having return type of the subclass

后端 未结 3 1684
遥遥无期
遥遥无期 2021-02-19 06:07

I am trying to create a set up where a set of subclasses override a superclass. This superclass contains an abstract method - the return type of which would ideally be that of t

3条回答
  •  面向向阳花
    2021-02-19 06:37

    How about this:

    public abstract class SuperClass> {
       public abstract T getSelf();
    }
    
    public class SubClass extends SuperClass {
         public SubClass getSelf() {
             return this;
         }
    }
    

    I know it's quite repetitive and nothing bounds the type to be the same SubClass instance, because also AnotherSubClass would satisfy the bound, but at least it should do the trick.

提交回复
热议问题