我可以像参数一样引用子类吗?
Can I refer to subclass like parameter?
我想在我的摘要 class 中提及任何潜在的 subclass 参数,以创建通用函数,例如创建 subclass 的新实例没有超载。
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);
}
}
我想在我的摘要 class 中提及任何潜在的 subclass 参数,以创建通用函数,例如创建 subclass 的新实例没有超载。
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);
}
}