Java Enum 使用

public class EnumLearn {
    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person();

        person1.setUsername("张三");
        person1.setGender(Gender.MALE);

        person2.setUsername("张娜拉");
        person2.setGender(Gender.FEMALE);

        System.out.println("person1: " + person1);  // person1: Person{gender=Gender{gender='男'}, username='张三'}
        System.out.println("person2: " + person2);  // person2: Person{gender=Gender{gender='女'}, username='张娜拉'}
        System.out.println("Gender.FEMALE: " + Gender.FEMALE);  // Gender.FEMALE: FEMALE
        System.out.println("Gender.MALE: " + Gender.MALE);  // Gender.MALE: MALE
        System.out.println(Gender.MALE == Gender.FEMALE);   // false
        System.out.println(Gender.MALE == Gender.MALE); // true
        System.out.println(Gender.MALE.getGender());    // 男
        System.out.println(Enum.valueOf(Gender.class, "FEMALE"));   // FEMALE
        System.out.println(Arrays.asList(Gender.values())); // [MALE, FEMALE]

        System.out.println("**************************");
        System.out.println("Gender2.FEMALE: " + Gender2.FEMALE.ordinal());
    }
}

/**
 * 枚举类似于单例设计,构造方法私有化
 */
enum Gender {
    MALE("男"), FEMALE("女");

    private String gender; // 枚举值【男/女】

    private Gender(String gender){
        this.gender = gender;
    }

    public String getGender(){
        return gender;
    }

}

enum Gender2{ MALE, FEMALE}

 

你可能感兴趣的:(JAVA)