Nelson Tatius
Nelson Tatius

Reputation: 8053

Which access modifier should I use for constants?

public static final

or

private static final

Considering cases when constants are used only from class itself. Which style is preferable?

Upvotes: 1

Views: 828

Answers (5)

M. Mott
M. Mott

Reputation: 11

If the constant only needs to be accessed in the class it is in, using

private static void 

or even just

static final

would work, since it is not needed to be called elsewhere.

However, if private static final is used for the constant, it is good practice to use a getter to call the constant, like this:

private static final String CONSTANTVARIABLE = "Some constant";

public String getConstantVariable() {
  return CONSTANTVARIABLE;
}

Upvotes: 1

SacJn
SacJn

Reputation: 777

Why don't you use enum for the same. They are actually designed to serve the purpose of constant along with flexibility to add functionality later if needed.

Just have a look at the following links to compare constants with enums , here and many more links you ll get. I just posted some of them.

Upvotes: 0

ZhongYu
ZhongYu

Reputation: 19682

Why not be lazy, and just do

    static final

I think it's better to start with 'package' access; you might needed it in unit test at least. Then you may change it to public/private or protected if you must.

'private' is usually not necessary - you seldom need to worry that other classes under the same package may screw up this class.

Upvotes: 0

jiaweizhang
jiaweizhang

Reputation: 819

private should be used when using multiple classes. You can use a getter if you need to access its value.

public should only really be used when you have just one class.

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37655

If you only need these values in the class, they should be private. In general make things as inaccessible as possible and only increase accessibility when necessary.

Upvotes: 1

Related Questions