为了账号安全,请及时绑定邮箱和手机立即绑定

我可以像参数一样引用子类吗?

我可以像参数一样引用子类吗?

繁星coding 2023-03-31 09:56:59
我想在我的抽象类中引用任何潜在的子类,如参数,以创建通用函数,例如在不重载的情况下创建子类的新实例。abstract class Fictional{  public static ArrayList<SUBCLASS_PARAM> subclassArray = new ArrayList<SUBCLASS_PARAM>();  int i;  private Fictional(int i) //All subclasses have to implement this constructor  {     this.i = i;     //body  }  public static SUBCLASS_PARAM loadFromFile() //I wouldn't have to override this method  {     SUBCLASS_PARAM subclass = new SUBCLASS_PARAM(1); //it's not possible to make new instance of abstract class, but it would be possible with any other subclass     subclassList.put(subclass);     return subclass;  }}class Real extends Fictional{//nothing here}class main{  Real r = Real.loadFromFile()}有什么办法可以做这样的事情吗?
查看完整描述

1 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

我想在我的抽象类中引用任何潜在的子类,如参数,以创建通用函数,例如在不重载的情况下创建子类的新实例。


abstract class Fictional

{

  public static ArrayList<SUBCLASS_PARAM> subclassArray = new ArrayList<SUBCLASS_PARAM>();

  int i;


  private Fictional(int i) //All subclasses have to implement this constructor

  {

     this.i = i;

     //body

  }


  public static SUBCLASS_PARAM loadFromFile() //I wouldn't have to override this method

  {

     SUBCLASS_PARAM subclass = new SUBCLASS_PARAM(1); //it's not possible to make new instance of abstract class, but it would be possible with any other subclass

     subclassList.put(subclass);

     return subclass;

  }

}


class Real extends Fictional

{

//nothing here

}


class main

{

  Real r = Real.loadFromFile()

}


有什么办法可以做这样的事情吗?


查看完整回答
反对 回复 2023-03-31
  • 1 回答
  • 0 关注
  • 100 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信