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

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


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()

}


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


繁星coding
浏览 101回答 1
1回答

MYYA

我想在我的抽象类中引用任何潜在的子类,如参数,以创建通用函数,例如在不重载的情况下创建子类的新实例。abstract class Fictional{&nbsp; public static ArrayList<SUBCLASS_PARAM> subclassArray = new ArrayList<SUBCLASS_PARAM>();&nbsp; int i;&nbsp; private Fictional(int i) //All subclasses have to implement this constructor&nbsp; {&nbsp; &nbsp; &nbsp;this.i = i;&nbsp; &nbsp; &nbsp;//body&nbsp; }&nbsp; public static SUBCLASS_PARAM loadFromFile() //I wouldn't have to override this method&nbsp; {&nbsp; &nbsp; &nbsp;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&nbsp; &nbsp; &nbsp;subclassList.put(subclass);&nbsp; &nbsp; &nbsp;return subclass;&nbsp; }}class Real extends Fictional{//nothing here}class main{&nbsp; Real r = Real.loadFromFile()}有什么办法可以做这样的事情吗?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java