1

I would like to refer in my abstract class to any potential subclass like to parameter, to make universal functions, that would for example make new instances of subclass without overloading.

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

Is there any way to make something like this ?

1 Answers1

0

You can do it with generics and subclases like this:

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);
    }
}
developer_hatch
  • 15,898
  • 3
  • 42
  • 75