简体   繁体   中英

How to let a derived class in a parameterized constructor chain access fields of the base class that are initialized using the derived constructor

I have a class Feedforward with a parameterized constructor of a configuration file:

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
    }

where the super(cfg) calls the constructor of the Network class, where I handle file parsing and storage of universal fields:

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

and when I run a test, it throws a NullPointerException. The type variable in Feedforward is not assigned with the value stored in the file at cfgPath/cfg, hence the exception. Why doesn't constructor chaining do this, and how can I do things differently?

Because type is local variable of a method (in this case constructor), though Network is a super class but we cannot access a local variable of any method out side it.

you can make String type=""; as a variable out side constructor , then just assign the value in side Network constructor.

and you can use it in Feedforward class.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM