什么时候我们应该使用“public static final String”? [英] when exactly are we supposed to use "public static final String"?

查看:255
本文介绍了什么时候我们应该使用“public static final String”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多代码,人们写 public static final String mystring = ...
然后只使用一个值。

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

为什么他们必须这样做?为什么他们必须在使用之前将值初始化为 final

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

UPDATE

好的,感谢所有答案,我理解这些关键字的意义(公共静态最终版)。我不明白为什么人们使用它,即使常量只在一个地方使用而且只在同一个类中使用。为什么要宣布呢?为什么我们不只是使用变量?

Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont 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 dont we just use the variable?

推荐答案

final 表示变量的值不会改变 - 换句话说,变量的值在声明之后无法修改。

final indicates that the value of the variable won't change - in other words, a variable who's value can't be modified after it is declared.

使用 public final static String 当你想要创建一个 String 时:

Use public final static String when you want to create a String that:


  1. 属于该类( static :没有必要使用它的实例),而且

  2. 不会改变( final ),例如,当您想要定义一个 String 常量时,该常量可供该类的所有实例以及使用该类的其他对象使用。

  1. belongs to the class (static: no instance necessary to use it), and that
  2. won't change (final), for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class.

示例:

public final static String MY_CONSTANT = "SomeValue";

// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)

同样:

public static final int ERROR_CODE = 127;

使用<$ c不是必需 $ c> final ,但它在程序执行期间不经意地更改保持不变,并作为变量是常量的指示符。

It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.

即使只使用常量 - 读取 - 在当前类和/或只在一个地方,最好将所有常量声明为 final :它更清晰,并且在代码的生命周期中,常量最终可能会在多个地方使用。

Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.

此外使用 final 可以允许实现执行一些优化,例如通过内联使用常量的实际值。

Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.

这篇关于什么时候我们应该使用“public static final String”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆