This document was copied literally for my own archival purposes. See references below.

In Java, when would you use private static final?

Simple Answer

Whenever you want to use a class-level constant.

Why?

Making a member private, means it's only visible to objects of the same class (unless, of course, expose via a public getter method).

Making it static means that there's only one instance of that particular member variable. This is good since there is no point having more than one instance of a constant.

Making it final, means that it can only be assigned once, allowing the compiler to optimize the byte code since it is known that the value of that variable is never going to change once assigned.

Complex Answer

You need to have a better reason to use private static final. A constant, if ever declared, is wasted if it is private. The basic reason for any constant's existence is to be reused, and to offer a one-point change. And if you want maximum reuse, you want to make that constant public. And probably move all constants to a separate class/interface, where they can be managed much more easily. You might even want to load the values of the constants from a properties or xml file, where they can be edited by someone who doesn't have or need access to the source code.

A more sensible use of private static final, is for a handle to a component like Log4J's Logger class if you want a category (represented by an instance of the Logger class) per class. You assign it only once and don't need more than one instance for each class. And it doesn't make sense to expose one class's logger object to another class. (Of course, you might want to think about having a category per method, rather than a category per class - for increased granularity and better log management.)

References

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.