Java 为什么我们使用常数?

Java 为什么我们使用常数?,java,android,Java,Android,为什么我们要在代码中使用常量并初始化它们?我不明白为什么我们要使用它们。例如: public class utils { public static final String BASE_URL = "api.openweathermap.org/data/2.5/weather?q="; public static final String ICON_URL = "api.openweathermap.org/data/2.5/weather?q="

为什么我们要在代码中使用常量并初始化它们?我不明白为什么我们要使用它们。例如:

  public class utils {

     public static final String BASE_URL = 
    "api.openweathermap.org/data/2.5/weather?q=";

    public static final String ICON_URL = 
    "api.openweathermap.org/data/2.5/weather?q="; }

有常量是很有帮助的,因此如果您以后想要进行更改,您不需要在代码中查找放置URL或其他内容的行。 您在一个位置更改它,对该常量的所有其他引用都是最新的

我希望我回答了你的问题


关于,

常量主要用于在一个地方维护和管理您的常量值。例如,如果要多次访问服务器url,我们可以避免多次声明同一url。有时,我们需要为Runnable设置延迟,此时我们可以创建常量值(即公共静态最终整数延迟=5000;)。用于所有可运行的。参见下面的示例

private static final Integer DELAY_TIME = 3000;
private Handler mHanlder = new Handler();

mHanlder.postDelayed(mAnimRunnable, DELAY_TIME)// Same Delay using one Constant variable.
mHanlder.postDelayed(mTextUpdateRunnable, DELAY_TIME)// Same Delay using one Constant variable.

private Runnable mAnimRunnable = new Runnable() {
        public void run() {
         //Your Animation Task  
        }
    };

    private Runnable mTextUpdateRunnable = new Runnable() {
        public void run() {
         //Your Text update Task  
        }
    };

与什么相反?只是在代码中内联那个字符串?因为现在这个字符串有了一个名称和一些语义含义,所以在整个代码中只有一个真实的来源。假设您切换到下一个API级别。在上面的代码中,您只需要在两个地方更改它(并且应该只有一个)。如果在调用API的任何地方都使用文本字符串,则必须修复所有这些时间。(在开发过程中,您没有输入错误。)它将很容易维护。它增加了可读性。您可以将所有常量值保持在同一位置。该类中的一个更改将反映到整个应用程序中。假设您想更改您的基本url。如果你内联url,你可能不得不到处转转,到处更改。但如果使用常量,代码中只需一行代码就可以更改。非常感谢您的帮助。我明白了