Why are Java constants declared static
?
class Foo {
static final int FII = 2 ;
}
In this example I understand the use of final
, But why does it have to be static? Why should it be a class variable and not an instance variable?
Why are Java constants declared static
?
class Foo {
static final int FII = 2 ;
}
In this example I understand the use of final
, But why does it have to be static? Why should it be a class variable and not an instance variable?
If a constant is not static, Java will allocate a memory for that constant in every object of the class (i.e., one copy of the constant per object).
If a constant is static, there will be only one copy of the constant for that class (i.e., one copy per class).
Therefore, if the constant has only one value, it should declared static.
If the constant might have different value for each object, for example the creation time of the object, it should not be declared static.
If it could vary by the instance of a class, then it's clearly not a constant. What would it mean to get a different value of pi for each instance of Math
(not that Math
even allows instances to be constructed)? Or a different case insensitive ordering for each instance of String
?
It is simply so that you can access them without an instance of that class.
Requiring that an instance be created just to access constant fields is a bit of a waste of resources.
Why are java constants declared static ?
Technically they aren't, JLS defines constants as final constant expression (which are referred to but not formally in java as compile time constant expression
). meaning a variable declared final which is initialized with a constant expression, meaning without static - https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.4
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression.
But the specification does not address anything regarding Constant Types which java is all about, Classes and Objects - so Jon Skeet answer regarding Math example is missing one part, Math class is considered constant because you cannot instantiate it by making its constructor private.
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Math.java -
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
public static final double PI = 3.14159265358979323846;
}
To support the Type itself being constant you need to make sure its state is also constant, but only for its members who are mutable and are exposed to changes from outside the type.
For example the literal PI is made public so it's available from outside the type. So to make sure it wont be changed from the outside it is made final, and also static so it will be part of the Class Class<Math> instance and could be exposed for use outside Math without the class being (explicitly) instantiated.