问题
Why are java constants declared static ?
class Foo{
static final int FII = 2 ;
}
In this I understand the use of final? Buy why does it have to be static? Why should it be a class variable, and not an instance variable?
回答1:
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
?
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/8093230/why-are-java-constants-declared-static