In projects we sometimes use constants, static constants and enumerations, so what are the differences between them? Let’s look at a few examples first:
According to the constants used in the framework:
/** 正常状态 */
public static final String NORMAL = "0";
/** 异常状态 */
public static final String EXCEPTION = "1";
/** 用户封禁状态 */
public static final String USER_DISABLE = "1";
/** 角色封禁状态 */
public static final String ROLE_DISABLE = "1";
/** 部门正常状态 */
public static final String DEPT_NORMAL = "0";
/** 部门停用状态 */
public static final String DEPT_DISABLE = "1";
/** 字典正常状态 */
public static final String DICT_NORMAL = "0";
If based on the enumeration used in the framework:
public enum UserStatus
{
OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除");
private final String code;
private final String info;
UserStatus(String code, String info)
{
this.code = code;
this.info = info;
}
public String getCode()
{
return code;
}
public String getInfo()
{
return info;
}
}
Constants: In Java, constants are declared using the keyword final. final means that this variable can only be assigned once. Once assigned a value, it cannot be changed.
Static constant: If you use static modification when defining a constant, then this constant is called a static constant. If you add public, then this constant can also be used in other classes.
Enumeration class: All enumeration types are subclasses of the Enum class. Enumerations are usually a group of instances that describe the same characteristics.
From the above definitions and examples it can be concluded that:
A single fixed value is usually represented by a constant; static constants can use public to modify the scope;
A set of values describing the same field is usually represented using an enumeration; an enumeration can initialize an instance.