Shang Silicon Valley_ Java zero foundation tutorial (common classes -- Enum classes) -- learning notes

1, Enum

I Use of enumeration classes

  1. Understanding of enumerating classes: there are only a limited number of objects in a class. For sure, we call this class enumerating class
  2. Enumeration classes are strongly recommended when you need to define a set of constants
  3. If there is only one object in the enumeration class, it can be used as an implementation of singleton mode

How to define enumeration classes

  • Method 1: jdk5 Custom enumeration class before 0
  • Mode 2: jdk5 0, enum keyword can be used to define enumeration class

1. Custom enumeration class

Attribute: private final
Object: private static final

matters needing attention:

  • a: Constructor privatization.
  • b: Inside this class, create a set of objects.
  • c: Exposed objects. (by adding the public static final modifier to the object)
  • d: You can provide a get method, but not a set method. Prevent modification.
package com.atguigu.java;

/**
 * 1, Use of enumeration classes
 * 1.The understanding of enumerating classes: there are only a limited number of objects in a class, which can be determined. We call this class enumeration class
 * 2.Enumeration classes are strongly recommended when you need to define a set of constants
 * 3.If there is only one object in the enumeration class, it can be used as an implementation of singleton mode.
 *
 * 2, How to define enumeration classes
 * Method 1: jdk5 Custom enumeration class before 0
 * Mode 2: jdk5 0, enum keyword can be used to define enumeration class
 *
 * 3, Common methods in Enum class:
 *    values()Method: returns an array of objects of enumeration type. This method can easily traverse all enumeration values.
 *    valueOf(String str): You can convert a string to the corresponding enumeration class object. The required string must be the name of an enumeration class object. If not, there will be a runtime exception: IllegalArgumentException.
 *    toString(): Returns the name of the object constant of the current enumeration class
 *
 * 4, The implementation of the interface using the enum class defined by the enum keyword
 *   Scenario 1: implement the interface and implement the abstract method in the enum class
 *   Case 2: let the objects of the enumeration class implement the abstract methods in the interface respectively
 *
 */
public class SeasonTest {

    public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);

    }

}
//Custom enumeration class
class Season{
    //1. Declare the attribute of Season object: private final modifier
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the constructor of the class and assign a value to the object attribute
    private Season(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //3. Provide multiple objects of the current enumeration class: public static final
    public static final Season SPRING = new Season("spring","in the warm spring , flowers are coming out with a rush");
    public static final Season SUMMER = new Season("summer","Summer heat");
    public static final Season AUTUMN = new Season("autumn","fresh autumn weather");
    public static final Season WINTER = new Season("winter","a world of ice and snow");

    //4. Other requirements 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
    //4. Other claims 1: toString()
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

2. Define enumeration classes using the keyword enum

After JDK 1.5, how to define enumeration classes using Enum keyword:
-1. Use the keyword enum instead of class.
-2.public static final AA spring = new AA("spring", 10)-- Simplified to - > spring ("spring", 10);
-3. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end
-4. If enum is used, the constant object to be defined is required, (spring("spring", 10);)

package com.atguigu.java;

/**
 * Define enumeration classes using enum keyword
 * Note: the defined enumeration class inherits from Java. Net by default Lang. enum class
 *
 */
public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer = Season1.SUMMER;
        //toString(): returns the name of the enumeration class object
        System.out.println(summer.toString());
        
        System.out.println("****************");
        //values(): returns an array of all enumeration class objects
        Season1[] values = Season1.values();
        for(int i = 0;i < values.length;i++){
            System.out.println(values[i]);
            values[i].show();
        }
        System.out.println("****************");
        Thread.State[] values1 = Thread.State.values();
        for (int i = 0; i < values1.length; i++) {
            System.out.println(values1[i]);
        }

        //valueOf(String objName): returns the object whose object name is objName in the enumeration class.
        Season1 winter = Season1.valueOf("WINTER");
        //If there is no enumeration class object of objName, throw an exception: IllegalArgumentException
//        Season1 winter = Season1.valueOf("WINTER1");
        System.out.println(winter);
        winter.show();
    }
}

interface Info{
    void show();
}

//Enum classes using enum keyword
enum Season1 implements Info{
    //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end
    SPRING("spring","in the warm spring , flowers are coming out with a rush"){
        @Override
        public void show() {
            System.out.println("Where is spring?");
        }
    },
    SUMMER("summer","Summer heat"){
        @Override
        public void show() {
            System.out.println("Ningxia");
        }
    },
    AUTUMN("autumn","fresh autumn weather"){
        @Override
        public void show() {
            System.out.println("Autumn doesn't come back");
        }
    },
    WINTER("winter","a world of ice and snow"){
        @Override
        public void show() {
            System.out.println("About winter");
        }
    };

    //2. Declare the attribute of Season object: private final modifier
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the constructor of the class and assign a value to the object attribute

    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4. Other requirements 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
//    //4. Other claims 1: toString() is provided
//
//    @Override
//    public String toString() {
//        return "Season1{" +
//                "seasonName='" + seasonName + '\'' +
//                ", seasonDesc='" + seasonDesc + '\'' +
//                '}';
//    }


//    @Override
//    public void show() {
//        System.out.println("this is a season");
//    }
}

Enum keyword precautions:
1. When we use the enum keyword to develop an enumeration class, we inherit the enum class by default, and it is a final class.

  • Single inheritance, but other interfaces can be implemented,
  • enum class is compiled into final java class at compile time

2. The traditional public static final AA spring = new AA("spring", 10), which is simplified to - > spring ("spring", 10);, You need to know which constructor to call.

3. If you create an enumeration object using a parameterless constructor, the argument list and parentheses can be omitted.

4. When there are multiple enumerated objects, the interval is used, and there is one at the end; ending.

enum BB {
    A, B, C;
}

5. Enumeration objects must be placed at the beginning of the line of the enumeration class. (spring("spring", 10);)

3. Main methods of Enum class

values()Method: returns an array of objects of enumeration type. This method can easily traverse all enumeration values.

valueOf(String str): You can convert a string to the corresponding enumeration class object. The required string must be the name of an enumeration class object. If not, there will be runtime exceptions: IllegalArgumentException. 

toString(): Returns the name of the object constant of the current enumeration class

demo1

public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer=Season1.SUMMER;
        //toString(): returns the name of the enumeration class object
        System.out.println(summer.toString());
        //Instead of overriding the tostring method, return the object name: SUMMER
        System.out.println(Season1.class.getSuperclass());
        //class java.lang.Enum
        System.out.println("****************");
        //values(): returns an array of all enumeration class objects
        Season1[] values=Season1.values();
        for (int i = 0; i <values.length ; i++) {
            System.out.println(values[i]);
        }
//SPRING
//SUMMER
//AUTUMN
//WINTER
        System.out.println("****************");
        Thread.State[] values1=Thread.State.values();
        for (int i = 0; i <values1.length ; i++) {
            System.out.println(values1[i]);
        }
// NEW
//RUNNABLE
//BLOCKED
//WAITING
//TIMED_WAITING
//TERMINATED
        System.out.println("****************");
        //valueOf(String objName): returns the object whose object name is objName in the enumeration class.
        Season1 winter=Season1.valueOf("WINTER");
        //If there is no enumeration class object of objName, throw an exception: IllegalArgumentException
        //Season1 winter=Season1.valueOf("WINTER1");
        System.out.println(winter);//WINTER

    }
}


demo2

    public static void main(String[] args) {
 
        // Returns an array of all enumerated class objects. Example: (view all status of threads)
        Thread.State[] values = Thread.State.values();
        // Output: [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED]
        System.out.println(Arrays.toString(values));
 
        // Returns the object named obj in the enumeration class according to the incoming obj name (find the object enumerated with the specified name)
        // If not found, an exception is thrown
        Thread.State waiting = Thread.State.valueOf("WAITING");
        System.out.println(waiting); //WAITING
 
 
        //Returns the name of the object constant of the current enumeration class
        String s1 = Thread.State.WAITING.toString();
        System.out.println(s1);  //WAITING
    }


4. Enumeration class that implements the interface

Scenario 1: implement the interface and implement the abstract method in the enum class

Case 2: let the objects of the enumeration class implement the abstract methods in the interface respectively

Situation 1

public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer=Season1.SUMMER;
        //toString(): returns the name of the enumeration class object
        System.out.println(summer.toString());
        //Instead of overriding the tostring method, return the object name: SUMMER
        System.out.println(Season1.class.getSuperclass());
        //class java.lang.Enum
        System.out.println("****************");
        //values(): returns an array of all enumeration class objects
        Season1[] values=Season1.values();
        for (int i = 0; i <values.length ; i++) {
            System.out.println(values[i]);
            values[i].show();
        }
//        SPRING
//        This is a season
//        SUMMER
//        This is a season
//        AUTUMN
//        This is a season
//        WINTER
//        This is a season
        System.out.println("****************");
        //valueOf(String objName): returns the object whose object name is objName in the enumeration class.
        Season1 winter=Season1.valueOf("WINTER");
        //If there is no enumeration class object of objName, throw an exception: IllegalArgumentException
        //Season1 winter=Season1.valueOf("WINTER1");
        System.out.println(winter);//WINTER
        winter.show();//This is a season

    }
}
interface Info{
    void show();
}
enum Season1 implements Info{
    //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end
    SPRING("spring","in the warm spring , flowers are coming out with a rush"),
    SUMMER("summer","Summer heat"),
    AUTUMN("autumn","fresh autumn weather"),
    WINTER("winter","a world of ice and snow");
    //2. Declare the attribute of Season object: private final modifier
    private final String seasonName;
    private final String seasonDesc;
    //3. Privatize the constructor of the class and assign a value to the object attribute
    private Season1(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }
    //4. Other requirements 1: get the properties of enumeration objects

    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

    @Override
    public void show() {
        System.out.println("This is a season");
    }
}

Situation II

public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer=Season1.SUMMER;
        //toString(): returns the name of the enumeration class object
        System.out.println(summer.toString());
        //Instead of overriding the tostring method, return the object name: SUMMER
        System.out.println(Season1.class.getSuperclass());
        //class java.lang.Enum
        System.out.println("****************");
        //values(): returns an array of all enumeration class objects
        Season1[] values=Season1.values();
        for (int i = 0; i <values.length ; i++) {
            System.out.println(values[i]);
            values[i].show();
        }
//SPRING
//It's spring
//SUMMER
//It's summer
//AUTUMN
//It's autumn
//WINTER
//It's winter
        System.out.println("****************");
        //valueOf(String objName): returns the object whose object name is objName in the enumeration class.
        Season1 winter=Season1.valueOf("WINTER");
        //If there is no enumeration class object of objName, throw an exception: IllegalArgumentException
        //Season1 winter=Season1.valueOf("WINTER1");
        System.out.println(winter);//WINTER
        winter.show();//It's winter

    }
}
interface Info{
    void show();
}
enum Season1 implements Info{
    //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is ";" end
    SPRING("spring","in the warm spring , flowers are coming out with a rush"){
        @Override
        public void show() {
            System.out.println("It's spring");
        }
    },
    SUMMER("summer","Summer heat"){
        @Override
        public void show() {
            System.out.println("It's summer");
        }
    },
    AUTUMN("autumn","fresh autumn weather"){
        @Override
        public void show() {
            System.out.println("It's autumn");
        }
    },
    WINTER("winter","a world of ice and snow"){
        @Override
        public void show() {
            System.out.println("It's winter");
        }
    };
    //2. Declare the attribute of Season object: private final modifier
    private final String seasonName;
    private final String seasonDesc;
    //3. Privatize the constructor of the class and assign a value to the object attribute
    private Season1(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }
    //4. Other requirements 1: get the properties of enumeration objects

    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

5. Enumerate usage scenario examples

Basic use of Java enumeration classes

Keywords: Java enum

Added by mhalloran on Sat, 18 Dec 2021 08:24:40 +0200