Enumeration class of Java foundation -- detailed explanation

Posted by JDBurnZ on Fri, 21 Jan 2022 21:25:27 +0100

Enumeration class of Java foundation - detailed explanation

1. User defined enumeration class

Introduce concepts:

When do we start using enumeration classes?

Introduce a small case:

We live in spring, summer, autumn and winter

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

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

The following is a code demonstration

class Seasons{
    private String name;
    private String desc;
      ///In this way, our data can not be modified externally
    private Seasons(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }
    public static final Seasons spring=new Seasons("spring","warm");//We use it internally and will not be modified. After optimization, we can add the final modifier
    //Write down by analogy to implement the operation of the custom enumeration class. Handle the name of the enumeration type in uppercase. Do not provide the get/set method, because the enumeration object is usually only readable
    //1. Privatization of constructors 2 Create a group of objects inside this class 3 External exposure object 4 You can provide get methods, but not set, so that our code will not be modified by the outside world.
}
2.enum

This is actually a class that helps us simplify. This class is optimized on the basis of our own custom writing to help our users have a better experience. Just change the class name to enum

Code demonstration

enum Seasons02{
    SPRING("spring","Warm."),//This sentence is equivalent to public static final Seasons spring=new Seasons("spring", "warm");
    WINTER("winter","cold"),
    private String name;
    private String desc;
    private Seasons02(String name,String desc){
        this.name=name;
        this.desc=desc;
    }
3. Enumeration precautions

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

2. It is better to use capital letters, which conforms to our specifications.

3. public static final keyword is hidden

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

5. If there are no parameters, we can omit the parentheses behind. For example, we can write summar directly.

We use javap to decompile to view our hidden content. You can clearly see that we are hiding public static final. We use decompile here

According to the normal process, we can directly from the source file to the bytecode file. Now that we use this decompile, we can change our class file into the source file, so that we can see our details more clearly.

4. Some methods in enum
Brief overview

For a brief overview, this is inherited by our enum class, which is equivalent to the existence form of a parent class,

We can directly use the methods inside. Let's see which methods are used first

1.name();
 Seasons02 spring = Seasons02.SPRING;//This side represents an object
 System.out.println(spring.name());//This will print the name of the enumeration

This will print the name of the enumeration constant we defined at that time. For example, we are SPRING now

2.ordinal();

This function helps us print out the number of our current enumeration object,

Let me show you the order of our definitions first

Then, according to the order we define, our system will assign values to them from 0

System.out.println(spring.ordinal());//The output is the order of the enumeration object, which actually means number. Our number starts from 0
3.values();

This method is interesting. It can return all our enumerated objects,

Let's look at the use of this function

Seasons02[] values = Seasons02.values();//In other words, this method will return our value and help us return the value

We will use an array to receive its return value. In fact, it returns all the defined data in this class

This method is then used in turn with the enhanced for loop

Enhanced for loop

Let's take a look at this writing first

int[]arr={1,2,3,4};
for(int i:arr){//This code is relatively concise. First, the function of this code is to output every element in the array. The first representative means that every element in our array is of type int. we name them i. This i is taken out of arr and taken in turn until there is no
//output
}

So let's take a look at the for loop, which traverses the enumeration class. In fact, it's just a change of type. Other basic functions have nothing to do with shaping arrays.

  Seasons02[] values = Seasons02.values();//In other words, this method will return our value and help us return the value
        for(Seasons02 seasons02:values){//This is the enhanced version of the for loop. / / this will
            System.out.println(seasons02);//Here is the default call to our tostring method (the tosting method of our parent class)
        }


4.valueOf();

This is another creation

//valueOf: to convert a string into an enumeration object, the string must be defined by us
Seasons02 seasons02 = Seasons02.valueOf("SPRING");//In this way, you can directly create an object as long as your string is our enumeration class
System.out.println(seasons02.name());
5.compareTo();

This function will cooperate with the ordinal (); Function use, this is a bad function

Let's see how this works first

 System.out.println(Seasons02.SPRING.compareTo(Seasons02.WINTER));//0-3 = - 3. This is our output - 3

We first write an object to call the compareTo function, and then we write another object we want to compare in the parameters.

The result is the first minus the second

Little practice

Description:

/statement week Enumeration class, which contains the definitions of Monday to Sunday, Monday . . . . . 
    //Ask you to use values to return all enumerated arrays and traverse

Code demonstration

You can see if you can write a prompt. If the tosting parent class is not easy to use, you can rewrite it yourself. At that time, you will call your own rewriting

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("Monday"),
    TUESDAY("Tuesday"),
    WEDNESDAY("Wednesday"),
    THURSDAY("Thursday"),
    FRIDAY("Friday");

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

    private String name;

    @Override
    public String toString() {//If the expected output effect is not achieved, we can consider rewriting the operation processing
        return "Week{" +
                "name='" + name + '\'' +
                '}';
    }
}
enum precautions

This class inherits all of Enum by default. This class cannot inherit other classes. Please note that multiple inheritance is not allowed in Java, but the interface can still be implemented, because we can implement multiple interfaces.

epilogue

Today, there are few knowledge points about enumeration classes, but they are still quite basic. They should be used later,

In my opinion, the enumeration class cannot be changed, that is, why do we have a public static final operation

It's a constant. You can think so. Then you can rewrite tostring when outputting, because name(); This print is your own name, so we still have to rewrite tostring.

Let's cheer together!!! Everyone thinks it's good. You can praise and support it.

Topics: Java Back-end