Enumeration classes in Java

The following are my notes on watching the Java learning video of shangsilicon valley

 

Enumeration class

  • Class has only a limited number of objects, which is uncertain. Examples are as follows:

    • Monday, Sunday
    • Gender: man (male), woman (female)
    • Season: Spring Festival... Winter
    • Payment methods: Cash (cash), WeChatPay (WeChat), Alipay (Alipay), BankCard (silver)
      Bank card), creditcard
    • Employment status: Busy, free Vocation,Dimission
    • Order status: unpaid, paid, fulfilled
      Delivered, return, Checked
    • Thread status: create, ready, running, blocking, dead
       
  • Enumeration classes are strongly recommended when you need to define a set of constants

  • If enumeration has only one object, it can be used as an implementation of the singleton mode.

  • Enumeration class properties

    • The properties of enumeration class objects should not be allowed to be changed, so private final should be used
    • The private final decorated property of an enumeration class should be assigned a value in the constructor
    • If the enumeration class explicitly defines a constructor with parameters, the corresponding incoming parameters must also be used when listing the enumeration values
       
  • Implementation of enumeration class

    • JDK1. You need to customize the enumeration class before 5
    • JDK1.5. The newly added enum keyword is used to define enumeration classes

 

Custom enumeration class

Sample code (definition):

import org.junit.Test;

//Custom enumeration class
class Season {
    //1. Declare the attributes of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //2. Constructor of privatization class
    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 2: get toString()
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

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

Output:

Season{seasonName ='spring ', seasonDesc ='spring flowers bloom'}

 

Define enumeration classes using enum keyword

Example code:

import org.junit.Test;

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

        System.out.println(Season.class.getSuperclass());
    }
}

//Enum classes using enum keyword
enum Season {
    //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is separated by " 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 attributes of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //3. Constructor of privatization class
    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

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

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

Output:

SPRING
class java.lang.Enum

Note that we did not override the toString method here, but when printing directly, we did not print the address value of the Object, but the name of the Object constant of the current enumeration class, indicating that the parent class of the Season class may not be the Object class. Therefore, we printed the parent class of the Season class and found that its parent class is class java Lang. enum class is not an Object class, so the toString method does not print the address value of the Object like the Object class.
 

Main methods of Enum class:

  • values() method: returns an array of objects of enumeration type. This method can easily traverse all enumerated values.
  • valueOf(String str): you can convert a string into a corresponding enumeration class object. Required character
    The string must be the name of an enumeration class object. If not, there will be runtime exceptions:
    lllegalArgumentException.
  • tostring(): returns the name of the object constant of the current enumeration class

Example code:

import org.junit.Test;

public class Sample {
    @Test
    public static void main(String[] args) {
        Season spring = Season.SPRING;

        //toString()
        System.out.println(spring.toString());//SPRING

        //values()
        Season[] values = Season.values();
        for (int i = 0; i < values.length; i++)
            System.out.println(values[i]);
        //Output:
        //SPRING
        //SUMMER
        //AUTUMN
        //WINTER

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

//Enum classes using enum keyword
enum Season {
    //1. Provide the object of the current enumeration class. Multiple objects are separated by "," and the end object is separated by " 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 attributes of the Season object
    private final String seasonName;
    private final String seasonDesc;

    //3. Constructor of privatization class
    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

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

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

 

Use enum keyword to define the enumeration class to implement the interface

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

Example code:

import org.junit.Test;

public class Sample {
    @Test
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        spring.show();//This is a season
    }
}

interface Info {
    void show();
}

//Enum classes using enum keyword
enum Season implements Info {
    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");

    private final String seasonName;
    private final String seasonDesc;

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

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

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

import org.junit.Test;

public class Sample {
    @Test
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        spring.show();//Where is spring?
    }
}

interface Info {
    void show();
}

//Enum classes using enum keyword
enum Season implements Info {
    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");
        }
    };

    private final String seasonName;
    private final String seasonDesc;

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

Keywords: Java Back-end

Added by Xurion on Thu, 20 Jan 2022 14:07:51 +0200