![](/img/trans.png)
[英]Why should the derived class constructor always access base class constructor?
[英]How to let a derived class in a parameterized constructor chain access fields of the base class that are initialized using the derived constructor
我有一个Feedforward类,带有配置文件的参数化构造函数:
public Feedforward(String cfg) throws Exception {
super(cfg);
String tempstr = "";
int currNeuronNum = 0;
int currEdgeNum = 0;
int currLayerID = 0;
int count = 0;
if (!(type).equals("feedforward")) {
throw new Exception("cfgError: specify proper type")
//more code
}
super(cfg)调用Network类的构造函数,在那里我处理文件解析和通用字段的存储:
protected Network(String cfgPath) throws IOException, Exception {
String type;
String activationFunction;
double bias;
/*file reading stuff; checked with print statements and during
the creation of a Feedforward class, successfully prints
"feedforward" after reading type from file
*/
}
当我运行测试时,它会抛出NullPointerException。 Feedforward中的类型变量未分配存储在cfgPath / cfg文件中的值,因此是例外。 为什么构造函数链不这样做,我怎么能以不同的方式做事?
因为type是方法的局部变量(在本例中是构造函数),虽然Network是一个超类但我们无法访问任何方法的局部变量。
你可以使String type =“”; 作为变量外部构造函数,然后只需在网络构造函数中分配值。
并且您可以在Feedforward类中使用它。
public class Network {
String type="";
protected Network(String cfgPath) throws IOException, Exception {
type=cfgPath;
String activationFunction=cfgPath;
double bias;
/*file reading stuff; checked with print statements and during
the creation of a Feedforward class, successfully prints
"feedforward" after reading type from file
*/
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.