user9352023
user9352023

Reputation:

When is it appropriate to use public instead of private when defining variables?

I have a list of constants that I would like to include at the top of my class. I first had the idea of using an enum to represent these constants so that they could be accessed at any time from any class.

However then I read that using public in this scenario would be appropriate as then other classes would be able to access the constants from within that class. Is this correct?

This is also leading me to ask the question; when is it appropriate to use the keyword public?

Upvotes: 0

Views: 65

Answers (1)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5581

Oleg is correct. Better create a separate environment class and declare all your constant there and import that package to a class where you want to utilize these constant. For example

package com.my.sys.variable;
 class EnvironmentVariable{
    public static final String CONFIG_FILE = "/app/myappl/myconfig.xml";
    //list of other varialbles
}

import com.my.sys.variable.EnvironmentVariable;

class Startup{
 LoadConfig(EnvironmentVariable.CONFIG_FILE);
 //your other codes

}

Upvotes: 2

Related Questions