我可以引用类似参数的子类吗?



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

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

有没有办法制作这样的东西?

你可以像这样使用泛型和子分支来做到这一点:

public abstract class Fictional<A extends Fictional> {
    public ArrayList<A> subclassArray = new ArrayList<A>();
    int i;
    public Fictional(int i) {
        this.i = i;
    }
    public A loadFromFile() //I wouldn't have to override this method
    {
        A subclass = this.build(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;
    }
    protected abstract A build(int i);
}
class Real extends Fictional
{
    public Real(int i) {
        super(i);
    }
    @Override
    protected Fictional build(int i) {
        return new Real(i);
    }
}

最新更新