本文介绍了Java泛型 - 覆盖抽象方法并具有子类的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图创建一组设置,其中一组子类覆盖超类。这个超类包含一个抽象方法 - 它的返回类型理想情况下是调用此方法的对象的返回类型,因此它的行为如下所示:

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 the object from which this method was called, such that it effectively behaves like this:

public abstract class SuperClass{
  public abstract SuperClass getSelf();
}

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

我不确定这样的事是否可能,因为我认为返回类型总是必须是相同的才能让重写工作 - 但是我一直在想如果存在的话,答案就在这条线上......

I am unsure if such a thing is possible, as I think return types always have to be the same in order for the override to work - however I have been thinking the answer, should one exist, lies somewhere along this line...

public abstract class SuperClass{
  public abstract <? extends SuperClass> getSelf();
}

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

感谢您的帮助。

edit:added extends SuperClass to SubClass,duh

edit: added extends SuperClass to SubClass, duh

推荐答案

这将起作用:

public abstract class SuperClass{
  public abstract SuperClass getSelf();
}

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

注意我已经添加了将SuperClass 扩展到您的 SubClass 定义。返回类型 getSelf 被称为 。

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

这篇关于Java泛型 - 覆盖抽象方法并具有子类的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 01:03