A:接口(Interface)的中变量默认为static final的特性
interface ConstantInterface {
String SUNDAY = “SUNDAY”;
}
B:Java 5.0中引入的Enum类型
enum ConstantEnum {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
C:在普通类中使用static final修饰变量的方法
class ConstantClassField {
public static final String SUNDAY = “SUNDAY”;
}
D:通过函数来获取常量
class ConstantClassFunction {
private static final String SUNDAY = “SUNDAY”;
public static String getSunday() {
return SUNDAY;
}
public static String getMonday() {
return MONDAY;
}
}
测试
public class TestConstant {
static final String day = “SUNDAY”;
public static void main(String[] args) {
System.out.println(day.equalsIgnoreCase(ConstantInterface.SATURDAY));
System.out.println(day.equalsIgnoreCase(ConstantEnum.SATURDAY.name()));
System.out.println(day.equalsIgnoreCase(ConstantClassField.SATURDAY));
System.out.println(day.equalsIgnoreCase(ConstantClassFunction.getSaturday()));
}
}