如何在Java中定义常量(Constant)
原本引自 http://blog.csdn.net/autofei/article/details/6419460
1 /** 2 * Method One 3 */ 4 interface ConstantInterface { 5 String SUNDAY = "SUNDAY"; 6 String MONDAY = "MONDAY"; 7 String TUESDAY = "TUESDAY"; 8 String WEDNESDAY = "WEDNESDAY"; 9 String THURSDAY = "THURSDAY"; 10 String FRIDAY = "FRIDAY"; 11 String SATURDAY = "SATURDAY"; 12 } 13 /** 14 * Method Two 15 */ 16 enum ConstantEnum { 17 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 18 } 19 /** 20 * Method Three 21 */ 22 class ConstantClassField { 23 public static final String SUNDAY = "SUNDAY"; 24 public static final String MONDAY = "MONDAY"; 25 public static final String TUESDAY = "TUESDAY"; 26 public static final String WEDNESDAY = "WEDNESDAY"; 27 public static final String THURSDAY = "THURSDAY"; 28 public static final String FRIDAY = "FRIDAY"; 29 public static final String SATURDAY = "SATURDAY"; 30 } 31 /** 32 * Method Four 33 * http://www.ibm.com/developerworks/cn/<a href="http://lib.csdn.net/base/17" class='replace_word' title="Java EE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>/l-java-interface/index.html 34 */ 35 class ConstantClassFunction { 36 private static final String SUNDAY = "SUNDAY"; 37 private static final String MONDAY = "MONDAY"; 38 private static final String TUESDAY = "TUESDAY"; 39 private static final String WEDNESDAY = "WEDNESDAY"; 40 private static final String THURSDAY = "THURSDAY"; 41 private static final String FRIDAY = "FRIDAY"; 42 private static final String SATURDAY = "SATURDAY"; 43 public static String getSunday() { 44 return SUNDAY; 45 } 46 public static String getMonday() { 47 return MONDAY; 48 } 49 public static String getTuesday() { 50 return TUESDAY; 51 } 52 public static String getWednesday() { 53 return WEDNESDAY; 54 } 55 public static String getThursday() { 56 return THURSDAY; 57 } 58 public static String getFirday() { 59 return FRIDAY; 60 } 61 public static String getSaturday() { 62 return SATURDAY; 63 } 64 } 65 public class TestConstant { 66 static final String day = "saturday"; 67 public static void main(String[] args) { 68 System.out.println("Is today Saturday?"); 69 System.out.println(day.equalsIgnoreCase(ConstantInterface.SATURDAY)); 70 System.out.println(day.equalsIgnoreCase(ConstantEnum.SATURDAY.name())); 71 System.out.println(day.equalsIgnoreCase(ConstantClassField.SATURDAY)); 72 System.out.println(day.equalsIgnoreCase(ConstantClassFunction 73 .getSaturday())); 74 } 75 }
方法一采用接口(Interface)的中变量默认为static final的特性
方法二采用了Java 5.0中引入的Enum类型。
方法三采用了在普通类中使用static final修饰变量的方法。
方法四类似方法三,但是通过函数来获取常量。
首先定义全局变量似乎有违Java的面向对象的封装特性,增加的耦合。所以最佳的方法是避免定义全局变量。如果是参数等,可以写入配置文件。如果实在是必须的,方法二是最为推荐的。方法三是大家都能想到的,非常的直观。方法一和方法三本质上一样。方法四提供了灵活性,具体参考引用【1】。
参考
http://www.ibm.com/developerworks/cn/java/l-java-interface/index.html
作者:SummerChill 出处:http://www.cnblogs.com/DreamDrive/ 本博客为自己总结亦或在网上发现的技术博文的转载。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |