Java basic enumeration class-detailed explanation

Java basic enumeration class – detailed explanation

Insert image description here

1. Custom enumeration class

Introduce concepts:

When did we start using enumeration classes?

Introducing a small case:

There are spring, summer, autumn and winter in our lives

Then these attributes are fixed and the names are not allowed to be modified. Then we can define a class ourselves for operation. This class,

It is not allowed to be accessed by the outside world and is not allowed to be modified. It is created by ourselves.

The following is a code demonstration

class Seasons{
    
    
    private String name;
    private String desc;
      ///这样一写的话 就可以使我们的这个数据变得不可以被外部修改了
    private Seasons(String name, String desc) {
    
    
        this.name = name;
        this.desc = desc;
    }
    public static final Seasons spring=new Seasons("春天","温暖");//我们在内部去使用,不会被修改 优化一下可以加入final修饰符
    //以此类推的书写下去  实现自定义枚举类的操作处理 枚举类型的名字使用大写  不要提供get/set方法 因为枚举对象通常只是可读的
    //1.构造器私有化 2.本类内部创建一组对象 3.对外暴漏对象 4.可以提供get方法,但是不要提供set,就是为了我们的代码不被外界修改。
}
2.enum

This is actually a class that helps us simplify. This class is optimized based on the customization we wrote ourselves to help our users have a better experience. We only need to change the class name to enum.

code demo

enum Seasons02{
    
    
    SPRING("春天","温暖的"),//这句话等同于 public static final Seasons spring=new Seasons("春天","温暖");
    WINTER("冬天","寒冷"),
    private String name;
    private String desc;
    private Seasons02(String name,String desc){
    
    
        this.name=name;
        this.desc=desc;
    }
3. Precautions for enumeration

1. When we write, our statement must be at the front

2. It is best to use uppercase letters and comply with our standards.

3. The public static final keyword is hidden

4. Inherit the Enum class by default. We will talk about the methods of this class later.

5. If there are no parameters, we can omit the following brackets. For example, we can just write SUMMER directly.

We use javap to decompile, and you can view our hidden content. You can clearly see that we have hidden public static final. We use decompilation here.

According to the normal process, we can directly go from source files to bytecode files. Now if we use this decompilation, we can change from class files to source files, so that we can see our files more clearly. detail.

Insert image description here

4. Some methods in Enum
Brief overview

To give a brief overview, this is inherited by our enum class, which can be equivalent to the existence form of a parent class.

We can directly use the methods inside. Let’s take a look at the methods below.

Insert image description here

1.name();
 Seasons02 spring = Seasons02.SPRING;//这边就代表一个对象
 System.out.println(spring.name());//这个就会打印枚举的名字出来

This will print out the name of the enumeration constant we defined at that time. For example, our current name is SPRING.

2.ordinal();

This function helps us print out what number our current enumeration object is located at.

Let me first show you the order of our definitions

Insert image description here

Then according to the order we defined, our system will assign values ​​to them starting from 0

System.out.println(spring.ordinal());//输出的是该枚举对象的次序 是第几个的意思 其实就是编号的意思 我们的编号从0开始
3.values();

This method is more interesting. It can return all our enumeration objects.

Let’s take a look at the use of this function

Seasons02[] values = Seasons02.values();//也即是说这个方法会返回我们的value值 会帮助我们返回数值出来

We will use an array to receive its return value. It actually returns all the data defined in this class.

Then this method is used in conjunction with the enhanced for loop.

Enhance for loop

Let’s take a look at this writing first

int[]arr={
    
    1,2,3,4};
for(int i:arr){
    
    //这个代码比较简洁 先说一下这个代码作用是把数组里面的每一个元素输出出来 第一个代表的意思是我们数组里面每一个元素都是int类型 我们给他们取名为i,这个i从arr里面取出来 依次去取直到没有
//输出
}

So let's take a look at this for loop, which traverses the enumeration class. In fact, it only changes the type. The rest basically has nothing to do with the integer array.

  Seasons02[] values = Seasons02.values();//也即是说这个方法会返回我们的value值 会帮助我们返回数值出来
        for(Seasons02 seasons02:values){
    
    //这个就是增强版for循环//这个会将一下
            System.out.println(seasons02);//这里是默认调用我们的tostring方法(我们父类的tosting方法)
        }


4.valueOf();

This is another creation

//valueOf: 将字符串转化为枚举对象,要求字符串必须为我们定义的才行
Seasons02 seasons02 = Seasons02.valueOf("SPRING");//这样直接创建一个对象,只要你的字符串是我们的枚举类就行
System.out.println(seasons02.name());
5.compareTo();

This function will cooperate with the ordinal() we mentioned before; function usage, this is a function that makes a difference

Let’s take a look at how this works first

 System.out.println(Seasons02.SPRING.compareTo(Seasons02.WINTER));//0-3=-3 这个就是我们的输出结果 -3

We first write an object and call the compareTo function, and then write the other object we want to compare as the parameter.

The result is the first minus the second

A little exercise

describe:

/声明week枚举类,其中包含的是星期一至星期日的定义,Monday 。。。。。
    //要求大家使用values返回所有的枚举数组,遍历

code demo

You can see if you can write a reminder that the tosting parent class is not easy to use and then rewrite it yourself. When the time comes, you will call your own rewrite.

public class EnumExerisice02 {
    
    
    public static void main(String[] args) {
    
    
        Week[] values = Week.values();
        for(Week week:values){
    
    
            System.out.println(week.toString());
        }
    }
}

enum Week{
    
    
    MONDAY("星期一"),
    TUESDAY("星期二"),
    WEDNESDAY("星期三"),
    THURSDAY("星期四"),
    FRIDAY("星期五");

    Week(String name) {
    
    
        this.name = name;
    }

    private String name;

    @Override
    public String toString() {
    
    //就是如果达不到预期的输出效果我们可以考虑一下重写的操作处理
        return "Week{" +
                "name='" + name + '\'' +
                '}';
    }
}
enum notes

This class inherits everything from Enum by default. This class cannot inherit other classes. Please note that multiple inheritance is not allowed in Java, but you can still implement interfaces because we can implement multiple interfaces.

Conclusion

There are relatively few knowledge points about enumeration classes today, but they are still relatively basic and should be used in the future.

I think the enumeration class is not allowed to be changed, which is why we have public static final operations.

It is a constant, you can think of it this way, and then you can rewrite tostring when outputting, because name(); this prints your own name, so we still have to rewrite tostring.

Let’s all work together! ! ! If you think it’s good, please give it a thumbs up and support it.

Insert image description here

Guess you like

Origin blog.csdn.net/SpongeBob_shouse/article/details/122628123