0

I'm struggling understanding how work with java objects from other objects. I have 3 simple classes: 1) environment object

public class Environment {

protected String envName;

public Environment(String envName){
    this.envName = envName;
}

// get and set methods
public String getenvName(){
    return envName;
}

public void setenvName(String envName){
    this.envName = envName;
}

}

2) Class that will populate this object

public class FetchConfig {

Environment environment;

public FetchConfig() {
}

public void buildConfig() {
    environment.setenvName("Steve");
}
}

3) A class with main method with will work with my Environment objects:

public class WorkWithEnvironment {

private FetchConfig config;

public static void main(String[] args) throws FileNotFoundException,
        IOException {

    WorkWithEnvironment w = new WorkWithEnvironment();
    w.setupConfig();
    w.readEnvNames();
}

private void setupConfig() throws FileNotFoundException, IOException {
    config = new FetchConfig();
    config.buildConfig();
}

private void readEnvNames() {

    System.out.println("Environment name is: "
            + config.environment.getenvName());
}

}

But when I run it, I keep getting an NPE(NullPointerException) here -> environment.setenvName("Steve");

1
  • 2
    Your FetchConfig class has a Environment field. If you don't initialize it for each instance, it remains null. Commented Mar 1, 2014 at 19:41

2 Answers 2

1

You've never told FetchConfig which Environment to use. I think you meant to have environment = new Environment(); or similar in FetchConfig's default constructor.

You could also initialize the variable environment with a similar line in the buildConfig method.

Sign up to request clarification or add additional context in comments.

Comments

0

Your second class is trying to set values inside your Environment Class before instantiating it and so it is null when you try to assign a value to it.

public class FetchConfig {

Environment environment;

public FetchConfig() {
    environment = new Environment(null);
}

public void buildConfig() {
    environment.setenvName("Steve");
}

2 Comments

Thx all -- actually it needed to be "Environment = new Environment(null); but I understand what I was doing incorrectly.
Edited my answer. Glad we could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.