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");
FetchConfigclass has aEnvironmentfield. If you don't initialize it for each instance, it remainsnull.