Search code examples
javaoopconstructorlanguage-concepts

How to instantiate an object using it's constructor outside a method java


I'd like to instantiate an object with it's constructor outside a method. Example:

public class Toplevel {

   Configuration config = new Configuration("testconfig.properties");

   public void method1() {

      config.getValue();
      ...etc
   }
}

If I do this right now...I get this error..

Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor

I'd like to do something like this so I could call config anywhere in my class, right now I keep having to instantiate the Configuration objects...there's gotta be a way to do this...any help would be much appreciated, thanks in advance.

EDIT:

Configuration class:

public class Configuration {

private String mainSchemaFile;


public Configuration() {
}

public Configuration( String configPath ) throws IOException {

    Properties prop = new Properties();
    prop.load( new FileInputStream( configPath ));

    this.mainSchemaFile= prop.getProperty("MAINSCHEMA_FILE");
}

Solution

  • When you create a new Toplevel object then you have not declared a specific constructor for it and the attribute of Toplevel is instantiated as your code describes it with Configuration config = new Configuration("testconfig.properties");

    So you do not handle the IoException of the Configuration constructor! A better way would be to declare a specific constructor of Toplevel like this:

    public Toplevel(){
        try{
            this.config = new Configuration("testconfig.properties");
        } catch (IOException e) {
            // handle Exception
        }
    }