It is a convention inherited from the C/C++ world that constants are named all uppercase. Since in Java, the closest equivalent of constant is static final
, these members are often named similarly.
In this case, the distinction may not be so important, since logger objects are semantically not constants. Nevertheless, it is still recommended to declare them static
to ensure you have a single instance per class, and you may want to declare them final
to ensure that the reference to the object can't be changed later (and to communicate this fact to readers of your code).
Update to @Moncader's comment:
static
is equivalent to C++ (class) static
- just as well as it does not make much sense in C++ to declare your constants as non-static, it does not make sense in Java either.
final
is not a direct equivalent of C++ const
. It means that the reference in question can not be changed. However, it does not prevent changing the object referred to! So it only works as const if it protects a primitive value (e.g. int
) or a reference to an immutable object (e.g. String
). To stay with our current topic, consider
private static final Logger logger = LoggerFactory.getLogger(Main.class);
...
logger.setLevel(Level.INFO);
logger.addAppender(...);
logger.setAdditivity(false);
All of these calls are obviously changing the state of the logger, even though it is declared final
. That's what I meant above by stating that logger objects are semantically not constants.