共有四种方式:
1 /** 2 * Method One 3 * 定义接口类,采用接口(Interface)的中变量默认为static final的特性。 4 */ 5 interface ConstantInterface { 6 String SUNDAY = "SUNDAY"; 7 String MONDAY = "MONDAY"; 8 String TUESDAY = "TUESDAY"; 9 String WEDNESDAY = "WEDNESDAY";10 String THURSDAY = "THURSDAY";11 String FRIDAY = "FRIDAY";12 String SATURDAY = "SATURDAY";13 }14 /**15 * Method Two16 * 定义枚举17 */18 enum ConstantEnum {19 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY20 }21 /**22 * Method Three23 * 定义常量类24 */25 class ConstantClassField {26 public static final String SUNDAY = "SUNDAY";27 public static final String MONDAY = "MONDAY";28 public static final String TUESDAY = "TUESDAY";29 public static final String WEDNESDAY = "WEDNESDAY";30 public static final String THURSDAY = "THURSDAY";31 public static final String FRIDAY = "FRIDAY";32 public static final String SATURDAY = "SATURDAY";33 }34 /**35 * Method Four36 * 定义bean37 */38 class ConstantClassFunction {39 private static final String SUNDAY = "SUNDAY";40 private static final String MONDAY = "MONDAY";41 private static final String TUESDAY = "TUESDAY";42 private static final String WEDNESDAY = "WEDNESDAY";43 private static final String THURSDAY = "THURSDAY";44 private static final String FRIDAY = "FRIDAY";45 private static final String SATURDAY = "SATURDAY";46 public static String getSunday() {47 return SUNDAY;48 }49 public static String getMonday() {50 return MONDAY;51 }52 public static String getTuesday() {53 return TUESDAY;54 }55 public static String getWednesday() {56 return WEDNESDAY;57 }58 public static String getThursday() {59 return THURSDAY;60 }61 public static String getFirday() {62 return FRIDAY;63 }64 public static String getSaturday() {65 return SATURDAY;66 }67 }68 69 /**70 * 测试代码71 * */72 class TestConstant {73 static final String day = "saturday";74 public static void main(String[] args) {75 System.out.println("Is today Saturday?");76 System.out.println(day.equalsIgnoreCase(ConstantInterface.SATURDAY));77 System.out.println(day.equalsIgnoreCase(ConstantEnum.SATURDAY.name()));78 System.out.println(day.equalsIgnoreCase(ConstantClassField.SATURDAY));79 System.out.println(day.equalsIgnoreCase(ConstantClassFunction.getSaturday()));80 }81 }
方法一采用接口(Interface)的中变量默认为static final的特性。
方法二采用了Java 5.0中引入的Enum(枚举)类型。
方法三采用了在普通类中使用static final修饰变量的方法。
方法四类似方法三,但是通过函数来获取常量,类似bean,也就是有自带的get方法。
使用常量类原因:
定义全局变量会增加程序耦合成都。最佳的方法是避免定义全局变量。如果是参数等,可以写入配置文件,否则方法二是最为推荐。方法三是比较直观。方法一和方法三本质上一样。方法四提供了灵活性。