[Java series] In-depth analysis of enumeration types

Preface

Even if there seems to be no waves in ordinary days, at a certain moment, persistent efforts will reveal its value and significance.

I hope this article will not only give you some gains, but also enjoy learning. If you have any suggestions, you can leave a message and communicate with me.

Question

Thinking about this question, we will start learning around these three questions:

  • what is enumeration
  • How to define an enumeration
  • Enumeration usage scenarios

1 What is an enumeration

A Java enumeration (Enum) is a special data type that is a set of predefined constants, each of which has a name and a value.

Enumeration types are widely used in Java, which can be used to replace constants, flags, status codes, etc., making the code clearer, easier to read and maintain.

The following is a detailed introduction to Java enumerations.

Use of 2 enumeration

Define enumeration type

In Java, an enumeration type can be defined by the keyword enum. The definition format of an enumeration type is as follows:

enum EnumName {
    Constant1,
    Constant2,
    Constant3,
    ...
}

Among them, EnumName is the name of the enumeration type, and Constant1, Constant2, Constant3, etc. are the constants of the enumeration type. Each enumeration constant has a name and a value. The names of enumeration constants are usually named in uppercase letters, and multiple words are separated by underscores.

Access enum constants

In Java, enumeration constants can be accessed by the name of the enumeration type. For example, assuming there is an enum type called Weekday, the enum constants can be accessed as follows:

Weekday monday = Weekday.Monday;

Here Weekday.Monday represents the Monday constant in the Weekday enumeration type.

Enumeration method

Enumeration types can define methods that can be called on enumeration constants. For example, you can define a isWeekend method in the Weekday enumeration type to determine whether the current enumeration constant is a weekend:

enum Weekday {
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;

    public boolean isWeekend() {
        return this == Saturday || this == Sunday;
    }
}

In the above example, by defining the method after the enum constant, the method can be called on each enum constant. For example, Weekday.Saturday.isWeekend() can be used to determine whether Saturday is a weekend.

Enumeration Constructor

Enumeration types can also define constructors, which can only be called in the definition of enumeration constants, and can only be used to initialize the value of enumeration constants. For example, you can define a constructor with parameters in the Weekday enumeration type to set the value of the enumeration constant:

enum Weekday {
    Monday("Monday"), Tuesday("Tuesday"), Wednesday("Wednesday"), Thursday("Thursday"), Friday("Friday"), Saturday("Saturday"), Sunday("Sunday");

    private String value;

    private Weekday(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

In the above example, by defining the constructor after the enum constant, it is possible to set the value for the enum constant in the definition of the enum constant. For example, you can use Weekday.Monday.getValue() to get the value of Monday.

Enumeration implements interface

Enumeration types can also implement interfaces, so that each enumeration constant automatically implements the methods in the interface. For example, you can define an interface in the Weekday enumeration type and have the enumeration type implement this interface:

interface Printable {
    void print();
}

enum Weekday implements Printable {
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;

    @Override
    public void print() {
        System.out.println("Today is " + this.name());
    }
}

In the above example, by making the Weekday enumeration type implement the Printable interface, each enumeration constant automatically implements the print method. For example, Weekday.Monday.print() can be used to output the current day of the week.

Summary

In summary, a Java enum is a strongly typed data type that provides a more elegant, clear and type-safe way to represent constants, status codes, etc.

Enumeration types can define constants, methods, constructors, and implement interfaces, which makes enumeration types very flexible and powerful. Enumeration types are widely used in Java, especially in the representation of state, options, etc., which can greatly improve the readability and maintainability of the code.

2 cases

Suppose we have a game with three characters: Warrior, Mage and Priest. Each character has its own attributes: health, attack and defense.

We can use the enumeration type to represent these three roles, the code is as follows:

Define role enumeration

public enum Role {
    WARRIOR("Warrior", 100, 50, 30),
    MAGE("Mage", 80, 70, 20),
    PRIEST("Priest", 60, 30, 50);

    private String name; // role name
    private int hp; // character HP
    private int attack; // character attack power
    private int defense; // character defense

    // Construction method
    private Role(String name, int hp, int attack, int defense) {
        this.name = name;
        this.hp = hp;
        this. attack = attack;
        this. defense = defense;
    }

    // getter method
    public String getName() {
        return name;
    }

    public int getHp() {
        return hp;
    }

    public int getAttack() {
        return attack;
    }

    public int getDefense() {
        return defense;
    }
}

In the above code, we defined an enumeration type named Role, which contains three enumeration constants: WARRIOR, MAGE and PRIEST. Each enum constant has its own properties: name, health, attack and defense. We also define a constructor that initializes these properties. Finally, we define getter methods for each property so that other classes can access these properties.

Define roles

Now, we can use the Role enumeration type in other classes to represent the role in the game. For example, we can write a Player class to represent players in the game, the code is as follows:

public class Player {
    private Role role; // player role

    public Player(Role role) {
        this.role = role;
    }

    public void attack(Player target) {
        int damage = this.role.getAttack() - target.getRole().getDefense();
        if (damage > 0) {
            int newHp = target.getRole().getHp() - damage;
            target.getRole().setHp(newHp);
        }
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }
}

In the above code, we defined a class called Player to represent the players in the game. Each player has a role, which we use the role field of the Role type to represent. In the constructor of the Player class, we need to pass in a parameter of type Role to initialize the player’s role.

The Player class also has an attack method, which is used to implement the player’s attack operation. In this method, we get the player’s attack power and defense power by calling the getAttack and getDefense methods, and then calculate the damage caused by the attack. If the damage value is greater than 0, update the HP of the target player. The Player class also has some getter and setter methods for accessing and modifying the player’s character.

Test

Now, we can write a simple test class to test the above code, the code is as follows:

public class GameTest {
    public static void main(String[] args) {
        Player player1 = new Player(Role. WARRIOR);
        Player player2 = new Player(Role.MAGE);

        System.out.println("Player 1 chose" + player1.getRole().getName());
        System.out.println("Player 2 chose" + player2.getRole().getName());

        player1. attack(player2);

        System.out.println("Player 2's HP is: " + player2.getRole().getHp());
    }
}

In the code above, we created two players, one with the fighter character selected and the other with the mage character selected. Then, we let player 1 attack player 2, and output player 2’s blood. Running this test class produces the following output:

Player 1 chose Warrior
Player 2 chooses the mage
Player 2's blood volume is: 60

From the output results, it can be seen that the attack of player 1 caused damage to player 2, and the blood volume of player 2 was reduced by the damage value obtained by subtracting the attack power from the defense power, and became 60.

Summary

In general, this case uses the enumeration type to represent the characters in the game, each character has its own attributes, and the enumeration type can be used in other classes to represent the role. Through this case, we can see that the use of enumeration types in Java is very flexible and can be used to represent any limited collection of constants.

Book recommendations

Java is 28 years old, when it is playing, and it will be playing for many years.

For you who are about to or are using Java, I recommend the Java “It’s a pity if you miss it in this life” series of books. See which one you still lack? Please complete.

Book list:

  • Java core technology 12th edition development foundation + advanced features (a set of 2 volumes)
  • Java Core Technology Version 11Edition< strong>Basic knowledge + advanced features (a set of 2 volumes)
  • Java programming thought [Thinking in Java]
  • Effective Java Chinese Edition (3rd Edition of the original book)
  • Java Language Programming Basics + Advanced (12th Edition of the original book) (a set of 2 volumes)
  • Java Concurrent Programming Actual Combat
  • Software Architecture Practice (4th Edition of the original book)

Java core technology 12th edition development foundation + advanced features (a set of 2 volumes)

The latest edition of Core Java, one of the “Four Great Masterpieces of Java”, packs a full set of 2 volumes with one click! It is recommended for beginners and developers who plan to upgrade to Java17 to purchase. This book is fully upgraded according to the new features of Java17! Free video lessons taught by the author + massive code sets.

You can take a sneak peek: “Java Core Technology 12th Edition Development Basics + Advanced Features (a set of 2 volumes)”

Java Core Technology Version 11Edition< strong>Basic knowledge + advanced features (a set of 2 volumes)

One of the “Four Great Masterpieces of Java”, the second new edition of Core Java, packs a full set of 2 volumes with one click! It is recommended that developers whose actual production environment is still using Java8 and Java11 to develop and have no plans to upgrade the version to purchase. This book is written based on Java9-11, and presents the author’s own video lessons + massive code sets.

Sneak peek: “Java Core Technology Volume 1 Basics + Java Core Technology Volume 2 Advanced Features (11th Edition of the original book)

Java programming thought [Thinking in Java]

One of the “Four Great Masterpieces of Java”, it needs to be read by people who have a certain programming foundation. Even if a lot of content is still incomprehensible, it will definitely gain something every time you finish reading it. The “Java Core Technology” recommended at the top of the book list focuses on technology, while “Java Programming Thoughts” focuses on “ideas”. This book analyzes the design concepts of various contents in Java for you. This is a good book that accompanies our technological growth. Buy one and put it next to it, and you will feel confident when you touch it.

Time-limited spike link: “Java Programming Thoughts (4th Edition)”

Effective Java Chinese Edition (3rd Edition of the original book)

James Gosling, the father of Java:

“I wish I had this book 10 years ago. Some people may think that I don’t need any books on Java, but I need this book.”

One of the “Four Great Masterpieces of Java”, it is suitable for programmers who have mastered the core technology of Java and developers who want to have a deeper understanding of the Java programming language. Provides the most practical and authoritative guidelines on how to write efficient and well-designed programs, explores new design patterns and language idioms through 90 short, independent rules of thumb, and helps you use the Java programming language and Its basic class library guides you to avoid detours. These rules of thumb cover solutions to problems that most developers face every day. It is an indispensable reference book on the desk of Java developers.

Time-limited spike link: “Effective Java Chinese Edition (3rd Edition of the original book)”

Java Language Programming Basics + Advanced (12th Edition of the original book)(A set of 2 volumes)

This set of books is more basic than “Java Core Technology”. If you are struggling to read “Java Core Technology”, it is recommended to start from this book. The “Book of the Great Wall”, which has been best-selling for more than 20 years, is packed with one click! Selected as a textbook by universities around the world, updated to Java9, 10 and 11. This book explains problem-solving skills through examples, provides a large number of program lists, and each chapter is equipped with rich review questions and programming exercises to help readers master programming techniques and solve problems encountered in actual development.

Time-limited flash kill link: “Java Language Programming Basics + Advanced (12th Edition of the original book) (a set of 2 volumes)”

Java Concurrent Programming Practice

Let you who focus on actual combat quickly understand the essentials of Java concurrent programming, and quickly build large-scale concurrent applications. Joshua Bloch, the author of “Effective Java”, one of the “Four Great Java Books”, participated in the writing. This book is a milestone work in the field of Java concurrent programming! Starting with the basic theory of concurrent programming, it gradually introduces various important design principles, design patterns and thinking patterns when designing Java concurrent programs. Another book “The Art of Java Concurrent Programming” written by Mr. Fang Tengfei of Ant Financial is also suitable for reading together.

Time-limited spike link: “Java Concurrent Programming Practice”

Software Architecture Practice (4th Edition of the original book)

A guide for advanced architects to avoid detours! Book Oscar Jolt Awards Double Crown Works! Published in more than 10 countries around the world. Carnegie Mellon and other famous school textbooks, top 10 books in IEEE magazine, de facto standards for software architecture books.

Time-limited spike link: “Software Architecture Practice (4th Edition of the original book)”

How to participate

Number of books: 5 books will be given out this time! ! !
Activity time: until 2023-05-29 12:00:00

Draw method:

  • 3 copies, leave a comment + the top three people with the number of likes in this comment will each get a copy!
  • 2 copies, random selection of friends in the comment area!
  • Message content: “Happy 28th birthday to Java!. + [The title of the book you want]”

Participation methods: Follow bloggers, like, bookmark, leave a message in the comment area

Winner list

Winners

Winner list: Please pay attention to blogger dynamics

Announcement time of the list: 2023-05-29 afternoon

Winning:

1. Stay up late and hack the code

2. YoLo

3. The Boys of Shuqian Street

4. Eat an apple

5. Java Learner ZGQ

Please contact the blogger in time with the winning friends

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeHome pageOverview 118794 people are studying systematically