Yogesh Gupta
Yogesh Gupta

Reputation: 1336

Java: Not able to access public member variable

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...
}

Upvotes: 0

Views: 64

Answers (1)

Yogesh_D
Yogesh_D

Reputation: 18764

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.

Upvotes: 8

Related Questions