Java basic enumeration (enum keyword)

foreword

Recently, I was reviewing the knowledge of the JavaSE part, recording some weak knowledge, learning methods, learning through videos and books, watching the video of Mr. Han Shunping's 30-day learning Java at station B, and reading the basic knowledge of Java core technology volume I in the book (original Book 10th Edition).

Han Shunping learned Java in 30 days Address: https://www.bilibili.com/video/BV1fh411y7R8?p=425
insert image description here

An introduction to enumeration

1. The derivation of enumeration (custom enumeration)

Requirement: Create a season object (Season) that contains the season name and description

package com.dudu.enumerone;

public class Season {
    
    
    private String name;
    private String desc;


    public Season(String name, String desc) {
    
    
        this.name = name;
        this.desc = desc;
    }


    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getDesc() {
    
    
        return desc;
    }

    public void setDesc(String desc) {
    
    
        this.desc = desc;
    }
}


class Test{
    
    
    public static void main(String[] args) {
    
    
        Season spring = new Season("春天","温暖");
        Season winter = new Season("冬天", "寒冷");
        Season summer = new Season("夏天", "炎热");
        Season autumn = new Season("秋天", "凉爽");

    }

}

The above code can fulfill our needs, but we can know that the season object is fixed (spring, summer, autumn and winter), and there will be no other seasons. If we add another Season object, this fixed will be broken. Season, obviously this way is not perfect!
insert image description here

Further improve
the analysis of the characteristics of the Season object:

  • The value of the season is a limited number of values ​​(spring, summer, autumn, winter)
  • read only, no modification required

According to the above characteristics, design the following code:

package com.dudu.enumerone;

public class Season {
    
    
    private String name;
    private String desc;

    public static final Season SPRING = new Season("春天","温暖");
    public static final Season WINTER = new Season("冬天", "寒冷");
    public static final Season SUMMER = new Season("夏天", "炎热");
    public static final Season AUTUMN = new Season("秋天", "凉爽");

    private Season(String name, String desc) {
    
    
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
    
    
        return name;
    }

    public String getDesc() {
    
    
        return desc;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public void setDesc(String desc) {
    
    
        this.desc = desc;
    }
}

class Test{
    
    
    public static void main(String[] args) {
    
    
        System.out.println("季节:"+Season.SPRING.getName()+"描述:"+Season.SPRING.getDesc());
        System.out.println("季节:"+Season.WINTER.getName()+"描述:"+Season.WINTER.getDesc());
        System.out.println("季节:"+Season.SUMMER.getName()+"描述:"+Season.SUMMER.getDesc());
        System.out.println("季节:"+Season.AUTUMN.getName()+"描述:"+Season.AUTUMN.getDesc());

    }

}

Running effect:
insert image description here
Note:
( 这里的不可修改表示的是无法改为指向其他对象,但其指向的对象本身是可以被修改的。)

Final modified reference objects cannot point to other objects: the
insert image description here
object itself can be modified:
insert image description here
running effects:
insert image description here

2. Use the enum keyword

Enumeration (enumeration, abbreviated enum) is a set of constants, belonging to a special class, which contains only a limited set of specific objects.

In the above code, the Season class contains nothing more than four sets of constant objects (spring, summer, autumn, winter), which are very consistent with the definition of enumeration, we can use the enum keyword to achieve.

package com.dudu.enumerone;

public enum SeasonEnum {
    
    
    SPRING("春天","温暖"),
    SUMMER("夏天","炎热"),
    AUTUMN("秋天","凉爽"),
    WINTER("冬天","寒冷")
    ;

   private SeasonEnum(String name, String desc) {
    
    
        this.name = name;
        this.desc = desc;
    }

    private String name;
    private String desc;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getDesc() {
    
    
        return desc;
    }

    public void setDesc(String desc) {
    
    
        this.desc = desc;
    }
}


class  Test_Enum{
    
    
    public static void main(String[] args) {
    
    
        System.out.println("季节:"+SeasonEnum.SPRING.getName()+"描述:"+SeasonEnum.SPRING.getDesc());
        System.out.println("季节:"+SeasonEnum.WINTER.getName()+"描述:"+SeasonEnum.WINTER.getDesc());
        System.out.println("季节:"+SeasonEnum.SUMMER.getName()+"描述:"+SeasonEnum.SUMMER.getDesc());
        System.out.println("季节:"+SeasonEnum.AUTUMN.getName()+"描述:"+SeasonEnum.AUTUMN.getDesc());
    }
}

running result:
insert image description here

We will find that SeasonEnum (using the enum keyword) is very familiar with the Season class designed above, with only two differences:

  • Season uses the Class keyword which is a class, while SeasonEnum uses the enum keyword

insert image description here

  • Constant objects in SeasonEnum are similar to Season's shorthand

insert image description here

In fact, the Season class is also a way to implement enumeration, that is, a custom enumeration type.
Season class decompiled source code:
insert image description here
SeasonEnum decompiled source code ( enum关键字本质上还是一个类(class),只是该类会继承Enum抽象类):
insert image description here

3. Notes (enum keyword implements enumeration)

  • When we use the enum keyword to develop an enumeration class, it will inherit the Enum class by default, and it is a final class
  • The traditional ( public static final Season SPRING = new Season("春天","温暖");) method is simplified to SPRING("春天","温暖"),, here you must know, which constructor it calls
  • If the enumeration object is created using the no-argument constructor, both the argument list and the parentheses can be omitted
  • When there are multiple enumeration objects, use the ,interval , and end with a semicolon at the end;
  • The enumeration object must be placed at the beginning of the enumeration line

If an enumeration object is created using the no-argument constructor, both the argument list and the parentheses can be omitted:
insert image description here
the enumeration object must be placed at the beginning of the enumeration line:
insert image description here

2. The use of enumeration

Requirements, use the no-argument constructor, create a color (Color) enumeration, containing three constants (RED, GREEN, YELLOW)

code show as below:

package com.dudu.enumerone;

public enum Color {
    
    
    RED,
    GREEN,
    YELLOW
    ;
}


class  Test_ColorEnum{
    
    
    public static void main(String[] args) {
    
    
        Color color = Color.RED;
        Color color1 = Color.RED;
        System.out.println(color);
        System.out.println(color == color1);
    }
}

running result:
insert image description here

  • The first output REDis the name returned by Color by calling the toString() method of the parent Enum class (the name here is RED)
    insert image description here
  • The second output returns true, this is because RED is a Static constant that acts on the class (the address and value are the same), and color and color1 point to the same address
    insert image description here

3. Common methods of enumeration

Description: When using the keyword enum, the Enum class will be implicitly inherited, so that we can use the related methods of the Enum class.
insert image description here

package com.dudu.enumerone;

public class EnumMethod {
    
    
    public static void main(String[] args) {
    
    
        // name():返回枚举对象的名字
        System.out.println(SeasonEnum.AUTUMN.name());
        // ordinal():返回枚举对象的次序(从0开始编号)
        System.out.println(SeasonEnum.AUTUMN.ordinal());

        // values():返回定义的所有枚举对象
        SeasonEnum[] seasonEnums =  SeasonEnum.values();
        for (SeasonEnum seasonEnum:seasonEnums){
    
    
            System.out.println(seasonEnum);
        }
        // valueOf():将字符串转换成枚举对象,要求该字符串必须为已有的常量名,否则会报错
        SeasonEnum seasonEnum = SeasonEnum.valueOf("SPRING");
        System.out.println(seasonEnum.getName());

        // compareTo():比较二个枚举常量,比较的是编号(前一个的编号减后一个的编号) self.ordinal - other.ordinal
        System.out.println("SPRING的编号为"+SeasonEnum.SPRING.ordinal());
        System.out.println("AUTUMN的编号为"+SeasonEnum.AUTUMN.ordinal());
        System.out.println("SPRING的编号 - AUTUMN的编号为"+(SeasonEnum.SPRING.ordinal()-SeasonEnum.AUTUMN.ordinal()));
        System.out.println("SPRING和AUTUMN比较的编号为"+SeasonEnum.SPRING.compareTo(SeasonEnum.AUTUMN));
    }
}

running result:
insert image description here

4. Enumeration usage details

  • After using the enum keyword, other classes cannot be inherited, because enum will implicitly inherit Enum, and Java is a single inheritance mechanism.
  • Like ordinary classes, enumeration classes can implement interfaces, such as:enum 类名 implements 接口1,接口2{}

After using the enum keyword, other classes cannot be inherited:
insert image description here

Like ordinary classes, enumeration classes can implement interfaces:
insert image description here

running result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_42753193/article/details/123961562