枚举类
前言
定义并使用枚举类型
枚举类型
1、枚举概念
枚举指由一组固定的常量组成的类型
2、枚举特点
1)类型安全
2)易于输入
3)代码清晰
3、实现操作
public class Student {
public String name;
public String sex;
public Student() {
}
public Student(String name, String sex) {
this.name = name;
this.sex = sex;
}
}
public class Test {
public static void main(String[] args) {
// 使用无参构造方法创建Student对象
Student student1 = new Student();
// 给属性赋值
student1.name = "张三";
student1.sex = "男";
Student student2 = new Student();
student2.name = "李四";
student2.sex = "您好";
// 直接给属性赋值,赋予的值可能不符合要求,所以需要对赋值进行判断
if(!(student2.sex.equals("男") || student2.sex.equals("女"))) {
System.out.println();
student2.sex = "女";
}
System.out.println(student2.sex);
// 枚举类型
}
}
运用枚举
public enum Gender {
// 枚举类
男,女
}
public class Student {
public String name;
public Gender sex;
public Student() {
}
public Student(String name, Gender sex) {
this.name = name;
this.sex = sex;
}
}
public class Test {
public static void main(String[] args) {
Student student1 = new Student();
student1.name = "张三";
// student1.sex = "男"; 报错
student1.sex = Gender.男; // 使用枚举类型
}
}
本文介绍了Java中的枚举类型,包括其概念、特点(如类型安全、易于输入和代码清晰),并通过示例展示了如何在类中使用枚举以及避免直接赋值可能导致的问题。最后,展示了如何定义和运用枚举类来提高代码质量。
731

被折叠的 条评论
为什么被折叠?



