private final int MAX = 100;
Does it have to be "private static final" instead of "private final"?
private final int MAX = 100;
Does it have to be "private static final" instead of "private final"?
static
has nothing to do with the fact that MAX
is final
. It just states whether every object of the class that defines this constant has "to have its own constant MAX
" (which wouldn't be really useful, since it's a constant), or if it's something that belongs to the class as a whole.
static
means this variable is a property of a class rather than of an object. For constants it is likely desirable to have it defined as static as they don't normally change/morph its values across different objects of given class - it is better to have one property created that is a class level rather than multiplying it across different objects of the class that would have the same value.
You save memory and you don't have to create objects to access their value.
Here is more information about static: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html and here is an answer to the question on how to define constants What is the best way to implement constants in Java?
The keyword private is referring to the visibility of the field/member(variable), final means once defined will never change its value, static means you don't actually need an object in order to use this value.
Conclusion:
private final int
can be a field/member of an object but you cant access to it from outside since is private. therefore you can never use this as a constant.
if you do:
foo.MAX
foo.getMax()
final
alone makes it constant, static
makes it use the same allocated space for every instance of the class it is in. When defining constants in Java, you should use both of them (that's probably you're having this confusion). Why you should use them both for defining constants? Because then you wouldn't have to create an instance of the class they're defined in AND if you do create an instance, they fill the same allocated space, thus you don't waste memory.