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

后端 未结 3 1689
遥遥无期
遥遥无期 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:47

    This will work:

    public abstract class SuperClass{
      public abstract SuperClass getSelf();
    }
    
    public class SubClass extends SuperClass{
      @Override
      public SubClass getSelf(){
        return this;
      }
    }
    

    Notice I've added extends SuperClass to your SubClass definition. The return type of getSelf is referred to as a covariant return type.

提交回复
热议问题