我是靠谱客的博主 斯文大地,最近开发中收集的这篇文章主要介绍在Java中定义常量(Constant) ,简化代码,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

/**
 * Method One,采用接口(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";
}
/**
 * Method Two ,引入的Enum类型。
 */
enum ConstantEnum {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
/**
 * Method Three,在普通类中使用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";
}
/**
 * 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()
));
}
}

最后

以上就是斯文大地为你收集整理的在Java中定义常量(Constant) ,简化代码的全部内容,希望文章能够帮你解决在Java中定义常量(Constant) ,简化代码所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部