0

I am struggling with access to a member variable and not able to find any explanation for it. If I call app.initDB(config) , it works; however when i call initDB() as is , config is null. Please look into code snippet to locate problematic line.

I was expecting config to be initialised as i am invoking it for app object here.

public class App {
    public RestConfig config;

    public App(RestConfig config) {
        config = config;
    }

    public void initDB() { // miss type returns
        System.out.println(config); // <-- prints null , why?**
    }
}

class RestMain {
    public static void main(String[] args) throws IOException {
        RestConfig config = new RestConfig();
        App app = new App(config);
        app.initDB();
    }

}

public class RestConfig {
    //some config...
}

1 Answer 1

8

You need to change your constructor to have this.config = config.

public App(RestConfig config){
        config = config;
      } 

Here what is happening is you are assigning the value of config to the passed value of config and not the class level variable.

What you need to do is this:

public App(RestConfig config){
        this.config = config;
      } 

And hence the class level variable/field stays null.

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

3 Comments

Good to see yogesh helping yogesh.
Any IDE worth using would have indicated a warning on this assignment. You should check to see if there was a warning, and if not, investigate how to turn on "self-assignment' warnings for your particular IDE. (And if you're not using an IDE... Consider that using one might help you catch bugs)
@Andy I use cscope for now, but I need to start using IDE.

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.