public class Base{
protected Base instantiate() {//Should return an instance of the subclass that this method has been called from
}
}
public class Sub1 extends Base {
}
public class Sub2 extends Base {
}
public static void main(String[] a) {
Sub1 sub1 = new Sub1();
Sub2 sub2 = new Sub2();
Sub1 ss = sub1.instantiate();//should return a new instance of Sub1
Sub2 s = sub2.instantiate();//should return a new instance of Sub2
}
如何在超类中实例化子类。换句话说,我需要知道上面代码中Base类中的instantiate()方法的实现。
修改:这是实际代码的一部分: 基类是:
/**
* Any class that extends this class should override the TABLE_NAME
*
* @author sSh
*/
public class Model {
protected static final String TABLE_NAME = null;
private void createRecord() throws ClassNotFoundException, SQLException {
}
private void updateRecord() {
}
public ResultSet getAllRecords() {
//This is the method--that returns instance of the subclass that this method has
// been called from
}
public void saveRecord() throws SQLException, ClassNotFoundException {
}
}
Model类应该是所有模型的Base类。 所以,如果我们有PatientModel,它将是这样的:
public class PatientModel extends Model{
protected static final TABLE_NAME = "patient";
//...fields and methods
}
public static void main(String[] a){
PatientModel.getAllRecords();//this will return all the records in patient table as patient objects
}
答案 0 :(得分:2)
你不能这样做,因为你不能覆盖静态方法。
您可以做的是创建一个执行此任务的BaseService类。
片段:
public class BaseService {
....
public static Base instantiate(Class<? extends Base> clazz) {
//create the new instance based upon the parameter
}
}
在main中:
Base base = BaseService.instantiate(Sub1.class);
或者如果你想将Sub1实例作为Sub1类型的变量,你应该强制转换。