What's the advantage of a Java enum versus a class with public static final fields?
Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum
however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf
.
What's difference between enums and final variables?
When you have an enum
like
public enum MyEnum {
FIRST_COSTANT, SECOND_CONSTANT;
}
What you actually have is
public class /* enum */ MyEnum extends Enum<MyEnum> {
private Enum() {}
public final static MyEnum FIRST_CONSTANT = new MyEnum() {};
public final static MyEnum SECOND_CONSTANT = new MyEnum() {};
... // methods
}
So in that sense, yes, they are the same.
This is explained in the Java Language Specification here.
In addition to the members that an enum type E inherits from Enum,
for each declared enum constant with the name n, the enum type has an
implicitly declared public static final field named n of type E. These
fields are considered to be declared in the same order as the
corresponding enum constants, before any static fields explicitly
declared in the enum type. Each such field is initialized to the enum
constant that corresponds to it. Each such field is also considered to
be annotated by the same annotations as the corresponding enum
constant. The enum constant is said to be created when the
corresponding field is initialized.
Are enums less maintainable than public static final constants?
I think you're taking the usage of enums way to far and then come to a conclusion that they are not useful.
Enums are simply telling you that there's a limited and predefined number of options to choose from. Nothing more than that. For example, when you see a parameter that is an enum (let's say State) and it has 3 values (Pending, InProgress, Closed), you know that a state of some object can have one of those and only one of those values.
Enums provide an easy way of validating that a proper value is used as you cannot easily select a value that is not proper when coding. They are also a way of documenting as you can easily see what options are available.
Why use Enums instead of Constants? Which is better in terms of software design and readability
Suppose you use constant strings (or int
values - the same goes for them):
// Constants for player types
public static final String ARCHER = "Archer";
public static final String WARRIOR = "Warrior";
// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";
then you end up not really knowing the type of your data - leading to potentially incorrect code:
String playerType = Constants.MALE;
If you use enums, that would end up as:
// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;
Likewise, enums give a restricted set of values:
String playerType = "Fred"; // Hang on, that's not one we know about...
vs
PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang!
Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.
Properties or Enums or static final
It all depends of your constant lifecycle.
Constant are by definition something that do not move. Choosing the right methods will be a question of the likely to change and the repackaging need.
If you're really sure, it wont move ever : static final is the way to go. Pi, mathematical constants, things like that are a good example.
If you think there is a potential change but need the ease of code manipulation and do not fear of ascendant compatibility, enums is ok. I did that for error code some time ago.
If you think there is a potential change but you don't want this change to impact your code, properties (with resource bundle) is the better choice. Labels (translations), inital settings, etc are also a good example.
What are the differences between a Java enum and a class with private constructor?
Differences:
- Enums extend
java.lang.Enum
and gain all of its nice features:- Automatic singleton behaviour through correct serialization
- Automatic human-readable
.toString
method on enum values without the need to duplicate your enum names .name
and.ordinal
special-purpose methods- Usable in high-performance bitset-based
EnumSet
andEnumMap
classes
- Enums are treated by the language specially:
- Enums use a special syntax which simplifies instance creation without writing dozens of
public static final
fields - Enums can be used in
switch
statements - Enums cannot be instantiated outside the enumeration list except by using reflection
- Enums cannot be extended outside the enumeration list
- Enums use a special syntax which simplifies instance creation without writing dozens of
- Java automatically compiles extra stuff into enums:
public static (Enum)[] values();
public static (Enum) valueOf(java.lang.String);
private static final (Enum)[] $VALUES;
(values()
returns a clone of this)
Most of these can be emulated with a suitably designed class, but Enum
just makes it really easy to create a class with this set of particularly desirable properties.
What's the advantage of a Java enum versus a class with public static final fields?
Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum
however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf
.
What's the advantage of a Java enum versus a class with public static final fields?
Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum
however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf
.
Related Topics
Add an Background Image to a Panel
Differencebetween Jvm, Jdk, Jre & Openjdk
Creation Timestamp and Last Update Timestamp with Hibernate and MySQL
Why Is String Immutable in Java
What Is the Maven-Shade-Plugin Used For, and Why Would You Want to Relocate Java Packages
How to Get a Thread and Heap Dump of a Java Process on Windows That's Not Running in a Console
In Java, What Are the Advantages of Streams Over Loops
Difference Between Each Instance of Servlet and Each Thread of Servlet in Servlets
Setting Default Values for Columns in JPA
Differencebetween a Javabean and a Pojo
Spring Boot Rest Service Exception Handling
When Would You Use a Weakhashmap or a Weakreference
What Is Simplest Way to Read a File into String
Performance of Java Matrix Math Libraries
How to Sort a List by Different Parameters at Different Timed
Should We @Override an Interface's Method Implementation