1. Basic concepts of enumeration
1. What is an enum?
Enumeration is used to defineA set of constantsThe type of , which is usually used to represent a series of fixed values. Java enumeration is throughenum
Keywords are defined, and each enum issubclass of .
2. Basic enumeration example
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
In this example,Day
Enumerations define 7 days of the week, each enum value (SUNDAY
、MONDAY
AllDay
Constant of type.
Example of usage:
Day today = ; if (today == ) { ("It's the start of the work week!"); }
3. Advantages of enumeration
- Type safety: Enumeration provides compile-time type checking to avoid errors caused by using strings or integer constants.
- readability: Enumeration makes the code more self-described and clarifies the specific business meaning.
- Scalability: Enumeration can define methods, fields, implement interfaces, etc., which is very flexible.
2. Advanced usage of enumeration
1. Fields and methods in enumeration
Enumerations can not only define constants, but also containFields、Constructorandmethod. In this way, enumerations can store more relevant information and execute logic as needed.
Example: Indicates whether the day of the week contains information about whether it is a working day
public enum Day { SUNDAY(false), MONDAY(true), TUESDAY(true), WEDNESDAY(true), THURSDAY(true), FRIDAY(true), SATURDAY(false); private final boolean isWorkday; // Constructor Day(boolean isWorkday) { = isWorkday; } public boolean isWorkday() { return isWorkday; } }
In this example, we define a Boolean field for each dayisWorkday
, used to indicate whether this day is a working day. Each enumeration constant needs to be assigned a value to this field when it is defined.
How to use:
Day today = ; if (()) { (today + " is a workday."); } else { (today + " is not a workday."); }
2. Add behavior to enums
You can define different behaviors for each enum constant, similar to the policy pattern. We can define abstract methods in the enum and provide a different implementation for each enum constant.
Example: Calculation of handling fees for different payment methods
public enum PaymentMethod { CREDIT_CARD { @Override public double calculateFee(double amount) { return amount * 0.02; // 2% handling fee } }, DEBIT_CARD { @Override public double calculateFee(double amount) { return amount * 0.01; // 1% handling fee } }, PAYPAL { @Override public double calculateFee(double amount) { return amount * 0.03; // 3% handling fee } }; // Abstract method, each enumeration constant needs to be implemented public abstract double calculateFee(double amount); }
How to use:
double amount = 1000.0; PaymentMethod method = PaymentMethod.CREDIT_CARD; double fee = (amount); ("Payment method: " + method + ", Fee: " + fee);
In this example, each payment method has its own specific fee calculation rules, and different behavioral logic is implemented through enumeration.
3. Enumeration implementation interface
Enumerations can not only contain methods, but also implement interfaces. This makes enumeration more flexible and can be used in some interface-oriented programming scenarios.
Example: Implementing a simple command mode with enumeration
public interface Command { void execute(); } public enum SimpleCommand implements Command { START { @Override public void execute() { ("Starting..."); } }, STOP { @Override public void execute() { ("Stopping..."); } }, RESTART { @Override public void execute() { ("Restarting..."); } } }
How to use:
SimpleCommand command = ; ();
Here,SimpleCommand
Enumeration is implementedCommand
interface and provide different implementations for each command. This design is ideal for scenarios with multiple states or commands.
4. Override the toString() method
The default for enumerationtoString()
The method will return the name of the constant. Sometimes we need to customize the output result, which can be overridden.toString()
method.
Example: Customize the display content of the enum
public enum Day { SUNDAY("Sunday"), MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"); private final String displayName; Day(String displayName) { = displayName; } @Override public String toString() { return displayName; } }
When using:
(); // Output: Monday
By overwritetoString()
Method, we can customize the output format of each enumeration constant.
3. Enumeration combined with switch statement
In Java,switch
Statements support enum types starting in version 1.5, which makes handling enumerations more concise.
Example: Conditional branching processing based on enum type
public class EnumSwitchExample { public static void main(String[] args) { Day today = ; switch (today) { case MONDAY: ("Back to work!"); break; case FRIDAY: ("Almost weekend!"); break; case SUNDAY: ("Rest and relax!"); break; default: ("Just another day."); break; } } }
In this case, useswitch
Statements can handle different values of enumerations more clearly and concisely.
4. Serialization and thread safety of enumerations
The enumeration in Java isSingle case, means that each enum constant has only one instance in the JVM, so they are essentially thread-safe. Even when serializing, Java enums are still singletons, because during deserialization, Java ensures that the same enum instance is returned.
Example: Enumeration as singleton pattern
public enum SingletonEnum { INSTANCE; public void doSomething() { ("Singleton doing something..."); } }
How to use:
SingletonEnum singleton = ; ();
Implementing singleton mode through enumeration not only concise code, but also ensures the security of serialization.
5. Summary
Java enumeration is not just a tool to define a set of constants, it can also be used to store data, implement methods, extend behavior, and even implement design patterns. Advanced usage of enumeration allows us to write clearer, maintainable and flexible code.
It is summarized as follows:
- Basic use: Enumeration is the best tool for defining constants to ensure type safety.
- Advanced Usage: Make enumeration more flexible through fields, methods and constructors.
- Implement interfaces and abstract methods: Enumerations can support different behavioral logic.
- Combined with switch: Convenient to judge conditions and the code is more concise.
- Thread Safety and Singleton Mode: The singleton feature of enumeration ensures thread safety and serialization safety.
Enumeration is not only a "constant collection", but also a highly expressive tool in the Java world.
This is the end of this article about the common techniques of Java enumeration. For more relevant Java enumeration usage techniques, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!