Why use constants instead of enums?
I've seen in lots and lots of Java libraries the use of lots of consta开发者_StackOverflownts where enums could have easily been used. Even in Swing, there is a lot of code that uses constants instead of enums. Why?
What are the disadvantages to using enums?
Because enums were introduced in Java 5, and those libraries have been written long before. Refactoring them would break a bazillion of existing applications.
- There is a lot of documentation of using pre-enum solutions.
- There are lots of developers who are using Java for the first time and have experience with another language where using constants is the norm.
- A lot of libraries wanted to support Java 1.4 and earlier. Java 1.3 & 1.4 are still used today.
- Working code hasn't been re-written just to use enums.
I find I still telling people to use enum for a Singleton even though it has been around for 7 years now. :P
When would use use constants instead of enum? When you have many associated but not directly related constants.
public static final int BUFFER_SIZE = 32 * 1024;
public static final String ERROR = "Error: ";
public static final char TAB = 't';
Enums in java are introduced in Java 5, these were not there before and Enum is equivalent to a class in java.
Prior to Java 1.5, there was no enum
in Java, and the most straight-forward way to implement the enum pattern was to use const ints. You can read more in the Java Tutorial section for enums.
精彩评论