首先看示例:
- /**
- * Method One
- */
- interface ConstantInterface {
- String SUNDAY = "SUNDAY";
- String MONDAY = "MONDAY";
- String TUESDAY = "TUESDAY";
- String WEDNESDAY = "WEDNESDAY";
- String THURSDAY = "THURSDAY";
- String FRIDAY = "FRIDAY";
- String SATURDAY = "SATURDAY";
- }
- /**
- * Method Two
- */
- enum ConstantEnum {
- SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
- }
- /**
- * Method Three
- */
- class ConstantClassField {
- public static final String SUNDAY = "SUNDAY";
- public static final String MONDAY = "MONDAY";
- public static final String TUESDAY = "TUESDAY";
- public static final String WEDNESDAY = "WEDNESDAY";
- public static final String THURSDAY = "THURSDAY";
- public static final String FRIDAY = "FRIDAY";
- public static final String SATURDAY = "SATURDAY";
- }
- /**
- * Method Four
- * http://www.ibm.com/developerworks/cn/java/l-java-interface/index.html
- */
- class ConstantClassFunction {
- private static final String SUNDAY = "SUNDAY";
- private static final String MONDAY = "MONDAY";
- private static final String TUESDAY = "TUESDAY";
- private static final String WEDNESDAY = "WEDNESDAY";
- private static final String THURSDAY = "THURSDAY";
- private static final String FRIDAY = "FRIDAY";
- private static final String SATURDAY = "SATURDAY";
- public static String getSunday() {
- return SUNDAY;
- }
- public static String getMonday() {
- return MONDAY;
- }
- public static String getTuesday() {
- return TUESDAY;
- }
- public static String getWednesday() {
- return WEDNESDAY;
- }
- public static String getThursday() {
- return THURSDAY;
- }
- public static String getFirday() {
- return FRIDAY;
- }
- public static String getSaturday() {
- return SATURDAY;
- }
- }
- public class TestConstant {
- static final String day = "saturday";
- public static void main(String[] args) {
- System.out.println("Is today Saturday?");
- 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()));
- }
- }
方法一采用接口(Interface)的中變量默認為static final的特性。
方法二采用了Java 5.0中引入的Enum類型。
方法三采用了在普通類中使用static final修飾變量的方法。
方法四類似方法三,但是通過函數來獲取常量。
首先定義全局變量似乎有違Java的面向對象的封裝特性,增加的耦合。所以最佳的方法是避免定義全局變量。如果是參數等,可以寫入配置文件。如果實在是必須的,方法二是最為推薦的。方法三是大家都能想到的,非常的直觀。方法一和方法三本質上一樣。方法四提供了靈活性,具體參考引用【1】。
參考
【1】http://www.ibm.com/developerworks/cn/java/l-java-interface/index.html