【问题标题】:How to let a derived class in a parameterized constructor chain access fields of the base class that are initialized using the derived constructor如何让参数化构造函数中的派生类链访问使用派生构造函数初始化的基类的字段
【发布时间】:2019-03-27 02:52:17
【问题描述】:

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

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。前馈中的类型变量未分配存储在 cfgPath/cfg 文件中的值,因此出现异常。为什么构造函数链接不这样做,我该如何做不同的事情?

【问题讨论】:

    标签: java object constructor constructor-chaining


    【解决方案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
              */       
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 2022-11-16
      • 2016-07-19
      • 2018-07-16
      相关资源
      最近更新 更多