I basically know how to use enum, but I want to go back to the source (discuss the essence)
Reject dogmatic excerpted document-style answers (time is important)
Looking for a deep understanding of enum (at least I have written a lot of code in the actual production environment)!
Note: I am not a beginner in programming, and some basic concepts do not require popular science
The object of discussion is enum in Java (actually enum is a concept)
Specifically, we are discussing the keyword enum
can be used instead of defining type constants, such as order status, certificate type, etc., to ensure type safety
For example, if the ordinary String class is used to represent the order status, the caller can pass a String that is not within the order status range to the callee. This This kind of error cannot be found in the compilation stage
Java enumeration class is essentially an implementation of multiple instance pattern, and singleton pattern is a special case of multiple instance pattern
Enumeration classes cannot be inherited. For example, enumA extends enumB cannot be used
An enumeration class with internal types in order implements the Comparable interface
Effective Java Chapter 6 has a detailed explanation, you can check it out
You can simply think of enum as an int type with remark information.
I’m shocked by your conditions, so I’ll just tell you my personal thoughts
enum can be regarded as a special class that contains some accessible and public constants. In fact, as accessible and public constants, they have been parsed into the constant pool during the class loading process. Enum only allows users to access the constants from a semantic perspective. Make it easier to show the meaning of constants when using them. At the same time, it also facilitates the construction of constants, looping through all constants of a certain type, using them in switch statements, etc.
This question is too broad and difficult to answer.
enum is essentially a class that inherits java.lang.Enum and can be used in singletons and where input needs to be limited
Let me first talk about my personal superficial and subjective understanding, and give some ideas.
I think the purpose of enum is:
Provide a means of managing constants,
A namespace.
The existence of enum itself is to solve the problem of readability of constants. Before there was no enum, to mark a state, the int type was often used. The readability of 1, 2 and so on was not very good, and a new constant was added. To write a long statement, this function was added in jdk5 to solve this series of problems. Its essence is a class, but when creating an enum, it will automatically generate values(), ordinal() and other methods, and supports switch statements, covering the scenarios where constants will appear. It is more convenient to use than directly defining constants.