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

前端 未结 11 1212
你的背包
你的背包 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:53

    It is kind of standard/best practice. There are already answers listing scenarios, but for your second question:

    Why do they have to do that? Why do they have to initialize the value as final prior to using it?

    Public constants and fields initialized at declaration should be "static final" rather than merely "final"

    These are some of the reasons why it should be like this:

    1. Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.

    2. Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.

提交回复
热议问题