7.3, Java enumeration enum

1 Enumeration import

Java is an object-oriented language. After we create a class, we can create multiple objects of this class.
But how many objects are created in a class, and we cannot limit the value represented by the object
. Therefore, if development needs A set of values, the required data is clear, you can use the enumeration

2 Enumeration concept

The enumeration class is a special form of Java class, and the number of objects of the enumeration class is limited and clear. for example:

Week: Monday (Monday)…Sunday (Sunday)
Gender: Man (Male), Woman (Female)
Season: Spring (Spring)…Winter (Winter)
Payment method: Cash (cash), WeChatpay (WeChat payment), AliPay ( Alipay payment), BankCard (bank card payment), CreditCard (credit card payment)
order status: Nonpayment (unpaid), Paid (paid), Fulfilled (allocated), Delivered (shipped), Return (returned), Checked (received)

Therefore, if we need to define a set of constants to represent different states, it is recommended to use the enumeration class.
JDK5 used to need to customize the enumeration class. After JDK5, the keyword enum can be used to define the enumeration class.
Let us first use the traditional class way to implement a custom enumeration class:

3 custom enumeration class

Each enumeration value declared in the enumeration class represents an instance object of the enumeration class.
Like ordinary classes in Java, when declaring an enumeration class, you can also declare properties, methods, and constructors,
but the constructor of the enumeration class It must be private, let's practice it together:

package cn.cxy.exec;
/*本类用于自定义枚举类*/
public class SeasonTest {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Season.SPRING.getSEASON_NAME());//春季
        System.out.println(Season.SUMMER.getSEASON_DESC());//夏日炎炎
        System.out.println(Season.AUTUMN);
        //Season{SEASON_NAME='秋季', SEASON_DESC='秋高气爽'}
    }
}
//1.自定义枚举类
class Season{
    
    
    //2.定义本类的私有属性,为了防止值被修改,需要设置为final
    private final String SEASON_NAME;//季节名
    private final String SEASON_DESC;//季节描述

    //3.私有化本类的构造方法--防止外界随意创建本类对象
    private Season(String seasonName,String seasonDesc){
    
    
        this.SEASON_NAME = seasonName;//在构造中给本类的属性赋值
        this.SEASON_DESC = seasonDesc;
    }

    //4.提供当前枚举类的多个对象
    public final static Season SPRING = new Season("春季","春暖花开");
    public final static Season SUMMER = new Season("夏季","夏日炎炎");
    public final static Season AUTUMN = new Season("秋季","秋高气爽");
    public final static Season WINTER = new Season("冬季","冬雪凛凛");

    //5.生成对应的get的方法,获取本类的两个属性值
    public String getSEASON_NAME() {
    
    
        return SEASON_NAME;
    }
    public String getSEASON_DESC() {
    
    
        return SEASON_DESC;
    }
    //6.生成toString方法方便查看

    @Override
    public String toString() {
    
    
        return "Season{" +
                "SEASON_NAME='" + SEASON_NAME + '\'' +
                ", SEASON_DESC='" + SEASON_DESC + '\'' + '}';
    }
}

4 Define an enumeration class using the keyword enum

package cn.cxy.exec;

/*本类用于使用enum关键字定义枚举类*/
public class ColorTest {
    
    
    public static void main(String[] args) {
    
    
        //6.进行测试
        System.out.println(Color.RED);//RED
        System.out.println(Color.ORANGE.getCOLOR_NAME());//橙色
        System.out.println(Color.ORANGE.getCOLOR_NUMBER());//2
    }
}

//1.使用enum关键字定义枚举类
enum Color {
    
    
    //2.写出本类对应的多个枚举对象
    /*1.public static final可以省略不写
    * 2.枚举对象不能像自定义枚举类对象时new,要按照下面的语法:
    * 枚举名1(值1,值2),枚举名2(值1,值2),枚举名3(值1,值2);
    * 3.不需要生成toString,因为使用enum关键字定义的枚举类继承了java.lang.Enum
    * 在Enum中重写了继承自Object的toString(),直接打印的就是枚举名*/
    RED("红色",1),
    ORANGE("橙色",2),
    YELLOW("黄色",3),
    GREEN("绿色",4),
    CYAN("青色",5),
    BLUE("蓝色",6),
    PURPLE("紫色",7);

    //3.定义枚举类的多个私有属性
    private final String COLOR_NAME;
    private final int COLOR_NUMBER;

    //4.定义本类的构造方法
    private Color(String colorName, int colorNumber) {
    
    
        this.COLOR_NAME = colorName;
        this.COLOR_NUMBER = colorNumber;
    }

    //5.生成属性对应的两个get()
    public String getCOLOR_NAME() {
    
    
        return COLOR_NAME;
    }
    public int getCOLOR_NUMBER() {
    
    
        return COLOR_NUMBER;
    }
}

Summarize:

Public static final can be omitted.
Enumeration objects cannot be new like custom enumeration class objects. Follow the following syntax:
enumeration name 1 (value 1, value 2), enumeration name 2 (value 1, value 2) , enumeration name 3 (value 1, value 2);
there is no need to generate toString, because the enumeration class defined with the enum keyword inherits java.lang.Enum and
rewrites toString() inherited from Object in Enum, directly What is printed is the enumeration name

5 Enumeration classes that implement interfaces

An enumeration class can also implement an interface or inherit an abstract class. There are two implementation schemes:
方案一:the enumeration class establishes an implementation relationship with the interface, and implements the abstract method defined in the interface in the enumeration class.
Effect: After each enumeration object calls the implementation The methods of the enumeration class and the interface establish an implementation relationship with the same effect
方案二:, and implement the abstract method after each enumeration object of the enumeration class.
Effect: different enumeration objects call the implemented method to have different effects

package cn.cxy.exec;
/*本类用于实现枚举实现接口*/
public class TestGame {
    
    
    public static void main(String[] args) {
    
    
        //8.进行测试
        Game.ROCK.show();//猜丁壳出的是石头
        Game.SCISSORS.show();//猜丁壳出的是剪刀
        Game.PAPER.show();//猜丁壳出的是布

        System.out.println(Game.ROCK.getName());//石头
        System.out.println(Game.ROCK.getNum());//0
    }
}
//6.定义接口与接口中的抽象方法
interface Info{
    
    
    void show();
}
//1.通过enum关键字定义枚举类
enum Game implements Info{
    
    
    //2.列出本类的枚举对象
    ROCK("石头",0){
    
    
        //7.2在每个枚举对象后实现接口的抽象方法
        public void show() {
    
    
            System.out.println("猜丁壳出的是石头");
        }
    },
    SCISSORS("剪刀",2){
    
    
        public void show() {
    
    
            System.out.println("猜丁壳出的是剪刀");
        }
    },
    PAPER("布",5){
    
    
        public void show() {
    
    
            System.out.println("猜丁壳出的是布");
        }
    };
    //3.定义本类的属性
    private final String name;
    private final int num;
    //4.创建本类的构造函数
    private Game(String name,int num){
    
    
        this.name = name;
        this.num = num;
    }
    //5.生成属性对应的get()
    public String getName() {
    
    
        return name;
    }
    public int getNum() {
    
    
        return num;
    }

    //7.1枚举实现接口抽象方法,方案一
//    @Override
//    public void show() {
    
    
//        System.out.println("猜丁壳游戏~");
//    }
}

6 The main method of the Enum class

String name() : returns the name of this enum constant, declare it in its enum declaration
int ordinal() : returns the ordinal of the enum constant (its position in the enum declaration, where the initial constant ordinal is zero )
static T valueOf(Class enumType, String name): Returns the enumeration constant of the specified enumeration type with the specified name
values(): Although this method cannot be found in the JDK documentation, every enumeration class has this method , which is used to iterate over all enumeration values ​​of the enumeration

package cn.cxy.exec;

import org.junit.Test;

import java.util.Arrays;

public class TestScore {
    
    

    //测试枚举的常用方法
    @Test
    public void test3() {
    
    
        //01-返回当前枚举值的名称
        System.out.println(Score.B.name());//B
        System.out.println(Score.B.toString());//B

        //02-打印当前枚举值在枚举类中声明的顺序
        System.out.println(Score.B.ordinal());//1,第2个枚举值

        /*使用场景:
         * 实际开发中表单提交过来的值是字符串类型,需要验证此字符串是否是我们定义的枚举值
         * 如果可以转换,说明提交的字符串没有问题,是我们预先定义好的枚举值
         * 如果不可以转换,说明提交过来的字符串有误,会报非法参数异常,没有这个枚举值*/
        //03-将字符串转成对应的枚举类型,注意这个类型必须是已有的枚举值
        //String str = "Cc";//IllegalArgumentException: No enum constant cn.tedu.oop.Score.Cc
        String str = "C";
        Score score = Score.valueOf(Score.class, str);
        System.out.println(score);
        //将字符串转成枚举类型的方式2,此种推荐,简单
        System.out.println(Score.valueOf(str));

        Score[] values = Score.values();
        System.out.println(Arrays.toString(values));

    }
}

//1.使用enum关键字定义枚举类
enum Score {
    
    
    //2.列出本类的多个枚举对象
    A("100-80") {
    
    
        //7.给每个枚举对象实现刚刚步骤6定义的抽象方法
        public String localeScore() {
    
    
            return "优";
        }
    }, B("79-60") {
    
    
        public String localeScore() {
    
    
            return "中";
        }
    }, C("59-0") {
    
    
        public String localeScore() {
    
    
            return "差";
        }
    };
    //3.定义一个私有的属性,封装每个对象对应的分数
    private final String score;

    //4.定义一个私有的构造函数
    private Score(String score) {
    
    
        this.score = score;
    }

    //5.定义一个输出成绩的抽象方法
    public abstract String localeScore();

    //6.定义一个公共的获取成绩的方法
    public String getScore() {
    
    
        return this.score;
    }
}

Note 1: If there is only one object in the enumeration class, it can be regarded as an implementation of the singleton mode

enum A {
    
    //相当于定义了一个类 class A;
    A;//相当于创建了这个类唯一的一个对象new A(); 类似于单例设计模式
}

Note 2: The switch statement is extended in JDK5, in addition to receiving byte short char int, it can also receive enumeration types

7 job requirements:

Write an enumeration WeekDay about the day of the week
Requirements: enumeration value: MON, TUE, WED, THR, FRI, SAT, SUN
This enumeration must have a method, calling this method returns the day of the week in Chinese format

package cn.tedu.oop;

import org.junit.Test;

public class Demo2 {
    
    
    @Test
    public void test(){
    
    
        //6.1拿到指定的枚举名
        System.out.println(WeekDay.MON);//MON
        //6.2拿到指定的枚举名对应的值
        System.out.println(WeekDay.MON.getValue());//星期一
    }
}
//1.定义枚举类
enum WeekDay {
    
    
    //2.定义枚举类中的枚举与其对应的值
    MON("星期一"), TUE("星期二"), WES("星期三"), THR("星期四"), FRI("星期五"), SAT("星期六"), SUN("星期日");
    //3.定义枚举类中的私有属性
    private String day;
    //4.定义枚举类的构造函数
    private WeekDay(String day) {
    
    
        this.day = day;
    }
    //5.定义枚举类的方法,并获取枚举对应的值
    public String getValue(){
    
    
        return this.day;
    }
}

Guess you like

Origin blog.csdn.net/weixin_58276266/article/details/131479329