why are java constants declared static?

限于喜欢 提交于 2019-11-27 02:30:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!