Java如何定义常量变量?
要在Java中定义常量,请使用final与static修饰符结合使用的修饰符。该final修饰符表明这个字段的值不能改变。
如果更改常量的值,则需要重新编译该类以获取当前值。Java中提供类似功能的其他功能是枚举(命名常量的列表)。您可以使用enum关键字简单地创建一个枚举。
package org.nhooo.example.fundamental;public class ConstantDemo {
public static void main(String[] args) {
int sunday = DayConstant.SUNDAY;
System.out.println("Sunday = " + sunday);
String dozen = MeasureConstant.DOZEN;
System.out.println("Dozen = " + dozen);
}
}
class DayConstant {
public final static int SUNDAY = 0;
public final static int MONDAY = 1;
public final static int TUESDAY = 2;
public final static int WEDNESDAY = 3;
public final static int THURSDAY = 4;
public final static int FRIDAY = 5;
public final static int SATURDAY = 6;
}
class MeasureConstant {
final static String UNIT = "unit";
final static String DOZEN = "dozen";
}
以上是 Java如何定义常量变量? 的全部内容, 来源链接: utcz.com/z/321405.html