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

前端 未结 11 1186
你的背包
你的背包 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 12:49

    static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.

    Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.

提交回复
热议问题