2Java面向对象编程——6java核心类——5枚举类
程序员文章站
2022-07-10 19:01:37
枚举类1.直接定义常量public class Main {public static void main(String[] args) {int day = 5;String color = "a";if (day == Weekend.FRI) {System.out.println(day);}if (color.equals(Color.BLUE)) {System.out.println(color);}}}clas...
枚举类
1.直接定义常量
public class Main {
public static void main(String[] args) {
int day = 5;
String color = "a";
if (day == Weekend.FRI) {
System.out.println(day);
}
if (color.equals(Color.BLUE)) {
System.out.println(color);
}
}
}
class Weekend{
public static final int SUN = 0;
public static final int MON = 1;
public static final int TUE = 2;
public static final int WED = 3;
public static final int THU = 4;
public static final int FRI = 5;
public static final int SAT = 6;
}
class Color{
public static final String RED = "r";
public static final String GREEN = "g";
public static final String BLUE = "b";
}
直接定义常量的缺点:编译器无法检查常量的内容,常量若发生改变,如将r变为R,很多逻辑会报错,因此java提供了枚举类型
2.使用enum定义常量
public enum Color{
RED,GREEN,BLUE;
}
编译器编译出的class:
public final class Color extends Enum{
public static final Color RED = new Color();
public static final Color GREEN = new Color();
public static final Color BLUE = new Color();
private Color(){
}
用enum定义常量
- 关键字enum定义常量类型
- 常量本身带有类型信息
- 使用“==”比较
enum定义的类型实际上是class
- 继承自java.lang.Enum
- 不能通过new创建实例
- 所有常量都是唯一实例(引用类型)
- 可以用swith语句
public enum Weekday {
SUN,MON,TUE,WED,THU,FRI,SAT;
}
public class Main {
public static void main(String[] args) {
for (Weekday day : Weekday.values()) {
// Weekday.values()获取所有常量的数组
System.out.println(day.name());//打印常量的name
}
Weekday fir = Weekday.FRI;//获取某个常量的引用类型
//获取name
System.out.println("FRI.name() = " + fir.name());//enum->String
//获取编号
System.out.println("FRI.ordinal() = " + fir.ordinal());
//Weekday.valueOf(String)获取某个指定的常量
System.out.println(Weekday.valueOf("FRI").name());//String->enum
System.out.println(Weekday.valueOf("ABC"));
}
}
还可以为枚举类添加字段和方法
public enum Weekday {
SUN("星期日"),
MON("星期一"),
TUE("星期二"),
WEN("星期三"),
THR("星期四"),
FRI("星期五"),
SAT("星期六");
private String chinese;
private Weekday(String chinese) {
this.chinese = chinese;
}
public String getChinese() {
return chinese;
}
}
public class Main1 {
public static void main (String[] args) {
Weekday fir = Weekday.FRI;
System.out.println(fir.toChinese());
}
}
3.总结
- enum可以定义常量类型,它被编译器编译为:final class Xxx extends Enum{..}
- name()获取常量定义的字符串,注意不要使用toString()
- ordinal()返回常量定义的顺序(无实质意义)
- 可以为enum类编写构造方法、字段和方法
- 构造方法申明为private
本文地址:https://blog.csdn.net/qq_24573381/article/details/107697365
上一篇: java入门~第九天 面向对象的继承
下一篇: 基于Netty手动模拟聊天室和RPC