我有很多 child 参加基础类,并计划增加更多 child 。我很懒。子创建者设置了 super 构造函数所需的一些基本内容,反之亦然。我的问题的一个简单解决方案如下:
parent {
public parent(){/*some code*/}
public void finalSetup(){/*code that dependent on the fact that the child constructor has run*/}
}
child{
public child(){/*some code;*/ super.finalSetup();}
}
然而,对每个 child 调用 super.finalSetup() 是相当麻烦的,如果我忘记在其中一个 child 上调用 super.finalSetup() ,它就会崩溃。那可不好。我的问题很简单:有没有办法从家长那里进行设置。就我的谷歌技能而言,我还没有找到一个。希望你们知道一些我不知道的事情。
谢谢
最佳答案
考虑工厂模式来创建扩展Parent的泛型类型。
public class Parent {
public Parent(){/*some code*/}
public void finalSetup(){/*code that dependent on the fact that the child constructor has run*/}
public static <T extends Parent> T makeChild(Class <T> klass) {
T child = null;
try {
child = klass.newInstance();
child.finalSetup();
}
catch (InstantiationException| IllegalAccessException ex) {
// somthing went wrong
}
return child;
}
}
并调用
Child child = Parent.makeChild(Child.class);
它在以下情况下很有用:
+ 类无法预测它必须创建的对象的类
+ 类希望其子类指定它创建的字段或对象
+ 类将责任委托(delegate)给多个辅助子类之一,并且您希望本地化哪个辅助子类是委托(delegate)的知识
关于java - 在java中调用父构造函数中的子构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762117/