when exactly are we supposed to use “public static final String”?

前端 未结 11 1185
你的背包
你的背包 2020-12-07 12:08

I have seen much code where people write public static final String mystring = ... and then just use a value.

Why do they have to do that? Why do they h

11条回答
  •  独厮守ぢ
    2020-12-07 13:02

    public makes it accessible across other classes. static makes it uniform value across all the class instances. final makes it non-modifiable value. So basically it's a "constant" value which is same across all the class instances and which cannot be modified. With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?" I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.

提交回复
热议问题