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

Does this definition make sense?

private static final String string = "Constant string";

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

+3
source share
4 answers

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

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

( privatehere means that this constant is available only for the current class (all its instances and its static methods))

+17
source

, - Java.

final , .

static , , . ()

, , :

private static final String CONSTANT_STRING = "Constant string";

.

+4

, ( "const" ), static , . , . , , , , .

+2

, , (, :)).

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

0
source

Source: https://habr.com/ru/post/1795745/


All Articles