javaobjectconstructorconstructor-chaining

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?


Solution

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