Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...