あなたはこれを行うことができます
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
ただし、どちらかを使用する必要は避ける必要があります。通常、ベースが暗黙的に派生に依存しないように、必要なことを行う別の方法があります。