我正在用Java构建一个基类/父类,它将有几种方法来创建类本身,我想知道是否有任何方法可以让父类返回子类的实例而不是返回父类的实例那一定要投给孩子吗?
例如,这是我的父类:
public abstract class SFObject
{
// Variables
protected String mID;
protected String mName;
// Function called to create ourselves from a DiffObject
public abstract SFObject CreateFromDiffObject(DiffObject object);
// Function called to create a list of ourselves from a query
public List<SFObject> CreateListFromQuery(Connection connection, String query)
{
// Run the query and loop through the results
ArrayList<SFObject> objects = new ArrayList<SFObject>();
for (DiffObject object : connection.Query(query))
objects.add(CreateFromDiffObject(object));
return objects;
}
}
如果我基于我的 SFObject 类创建一个子类,我的子类中的两个函数仍将返回一个 SFObject(需要转换为我的子类类型)或 SFObject 列表(需要单独转换为我的子类类型)。有什么方法(可能使用反射)让我的子类返回自身的实例而不是 SFObjects?