提问者:小点点

如何让参数化构造函数链中的派生类访问使用派生构造函数初始化的基类的字段


我有一个带有配置文件的参数化构造函数的类反馈:

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
    }

其中超级(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。反馈中的类型变量没有被赋予存储在cfgPath/cfg文件中的值,因此出现了异常。为什么构造函数链接不这样做,我如何以不同的方式做事?


共1个答案

匿名用户

因为type是方法的局部变量(在本例中为构造函数),虽然Network是一个超类,但我们不能访问它之外任何方法的局部变量。

您可以使String type="";作为变量端外构造函数,然后只需在端网络构造函数中分配值。

您可以在前馈类中使用它。

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
          */       
    }
}