二、类
1、Enum 枚举
- java 语言所有枚举类型的公共类;
- 枚举用来替换使用常量表示列入颜色、方式、类别等数量有限,形式离散有表示明确的量;
- 枚举是类型安全的,超出枚举类型的返回,将会发生编译时错误;
例:
- 使用常量来表示颜色:
public class Entity{
public static final int red = 1;
public static final int white = 2;
public static final int blue = 3;
private int id;
private int color;
public Entity(int id, int color){
this.id = id;
this.color = color;
}
//id与color的getter 和setter方法
...
}
实例化一个Entity对象时:
Entity entity = new Entity();
entity.setId(10);
entity.setColor(1);
或者:
Entity entity = new Entity();
entity.setId(10);
entity.setColor(Entity.red);
使用第一种方式,代码的可读性低,1到底代表的什么颜色,需要到Entity类中查看;
使用第二种方式,同样需要去Entity类中查看代码,才能知道怎么调用,参数要怎么传。
- 使用枚举来表示颜色
//Color.java
package com.heisenberg.Learn;
public enum Color {
red,blue,white
}
//Entity.java
package com.heisenberg.Learn;
public class Entity {
private Color color;
private int id;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public static void main(String[] args) {
Entity entity = new Entity();
entity.setId(10);
entity.setColor(Color.blue);
}
}
使用枚举,代码的可读性提升了,并且在给color赋值时,只能选择Color枚举类中定义的三个选项,所以枚举是类型安全的,如果使用了另外的值,将出现编译错误。
- java中的枚举是一个类,所以枚举也可一后构造函数和其他的方法;只是枚举继承了Enum类,所以它不能再继承其它的类。
- 如果给每个枚举值指定属性,则必须给枚举类提供枚举值属性对应数据类型的构造方法。如下,Color的每个枚举值都带有一个int和一个String类型的属性,则必须提供Color(int value,String name)的构造方法;属性的名称不受限制,但是属性的类型要一一对应。
//Color.java
package com.heisenberg.Learn;
public enum Color {
red(1,"红色"),blue(2,"蓝色"),white(3,"白色");
int value;
String name;
private Color(int value, String name) {
this.value = value;
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
Entity entity = new Entity();
entity.setId(10);
entity.setColor(Color.blue);
System.out.println(entity.getColor().getValue());
System.out.println(entity.getColor().getName());
}
运行的结果为:
2
蓝色