开发者

Does it make sense to define a static final variable in Java?

Does this definit开发者_运维问答ion make sense ?

private static final String string = "Constant string";

I'm a beginner and I don't understand the difference between final and static...


It makes sense, yes. This is how constants are defined in Java.

  • final means that the variable cannot be reassigned - i.e. this is the only value it can have
  • static means that the same value is accessible from each instance of the class (it also means it can be accessed even without an instance of the class where it is declared)

(private here means this constant is accessible only to the current class (all of its instances and its static methods))


Yes, it makes sense - this is how constants are usually defined in Java.

final means that you cannot change the variable to a different String.

static means that there is only one copy of the reference, shared between different objects of that class. (reference)

Normal code-convention is that constants are named in uppercase with underscores between words, so I would say:

private static final String CONSTANT_STRING = "Constant string";

is more common.


Final means the value can't change (it's "const"), whereas static means it's a property of the class itself, rather than of an instance of the class. So yes, that kind of definition makes sense, and indeed is very common. Final constants like this tend to be static too, as there's little point in having them as instance properties as they can't change.


it's an old question, but i will add an information here for someone who find out this post(like me :)).

Yes it makes sense for a class member to be static and final, but it's nonsense if the variable is declared static in a method(a compile-time error launches).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜