你可以这样做
public class Derived extends Base {
public static void main(String ... args) {
System.out.println(new Derived().createInstance());
}
}
abstract class Base {
public Base createInstance() {
//using reflection
try {
return getClass().asSubclass(Base.class).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
印刷
Derived@55fe910c
更常见的模式是使用 Cloneable
public class Derived extends Base {
public static void main(String ... args) throws CloneNotSupportedException {
System.out.println(new Derived().clone());
}
}
abstract class Base implements Cloneable {
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
印刷
Derived@8071a97
但是,应避免使用其中任何一个。通常还有另一种方法可以做你需要的事情,这样 base 就不会隐式地依赖于派生。