只要是懂java开发的小伙伴,相信你们对java中的常量应该不会陌生吧,没错,今天呢小编就会带着感兴趣的朋友一起来看看,java中常量定义都有哪些方法呢?我们怎么去实现呢?
方法一,采用接口(Interface)的中变量默认成为static final的特性:
interface ConstantInterface { String SUNDAY = "SUNDAY"; String MONDAY = "MONDAY"; String TUESDAY = "TUESDAY"; String WEDNESDAY = "WEDNESDAY"; String THURSDAY = "THURSDAY"; String FRIDAY = "FRIDAY"; String SATURDAY = "SATURDAY"; }
方法二,采用了java5.0中引入了Enum类型:
enum ConstantEnum { SUNDAY , MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY , SATURDAY }
方法三,采用了在普通类中使用static final修饰变量的方法:
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"; }
方法四,类似方法三,但是通过函数来获取常量:
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())); } }
首先呢定义全局变量似乎有违Java中的面向对象的封装特性,增加了耦合。所以最佳的方法是避免定义全局的变量。如果是参数这些,可以写入配置文件。如果说实在是必须的,方法二其实是最为推荐的。方法三是大家都能想到的,非常的直观。总的来说,方法一和方法三本质上一样。方法四提供了灵活性。
那么以上就是java常量定义的所有内容了,还想了解更多java入门知识,记得多多关注本站消息哦。