How do you define a class of constants in Java? - java

Suppose you need to define a class which all it does is hold constants.
public static final String SOME_CONST = "SOME_VALUE";
What is the preferred way of doing this?
Interface
Abstract Class
Final Class
Which one should I use and why?
Clarifications to some answers:
Enums - I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way.
Interface - I'm not going to set any class as one that implements the interface. Just want to use the interface to call constants like so: ISomeInterface.SOME_CONST.

Use a final class, and define a private constructor to hide the public one.
For simplicity you may then use a static import to reuse your values in another class
public final class MyValues {
private MyValues() {
// No need to instantiate the class, we can hide its constructor
}
public static final String VALUE1 = "foo";
public static final String VALUE2 = "bar";
}
in another class :
import static MyValues.*
//...
if (VALUE1.equals(variable)) {
//...
}

Your clarification states: "I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way."
If the constants aren't related to each other at all, why do you want to collect them together? Put each constant in the class which it's most closely related to.

My suggestions (in decreasing order of preference):
1) Don't do it. Create the constants in the actual class where they are most relevant. Having a 'bag of constants' class/interface isn't really following OO best practices.
I, and everyone else, ignore #1 from time to time. If you're going to do that then:
2) final class with private constructor This will at least prevent anyone from abusing your 'bag of constants' by extending/implementing it to get easy access to the constants. (I know you said you wouldn't do this -- but that doesn't mean someone coming along after you won't)
3) interface This will work, but not my preference giving the possible abuse mention in #2.
In general, just because these are constants doesn't mean you shouldn't still apply normal oo principles to them. If no one but one class cares about a constant - it should be private and in that class. If only tests care about a constant - it should be in a test class, not production code. If a constant is defined in multiple places (not just accidentally the same) - refactor to eliminate duplication. And so on - treat them like you would a method.

As Joshua Bloch notes in Effective Java:
Interfaces should only be used to define types,
abstract classes don't prevent instanciability (they can be subclassed, and even suggest that they are designed to be subclassed).
You can use an Enum if all your constants are related (like planet names), put the constant values in classes they are related to (if you have access to them), or use a non instanciable utility class (define a private default constructor).
class SomeConstants
{
// Prevents instanciation of myself and my subclasses
private SomeConstants() {}
public final static String TOTO = "toto";
public final static Integer TEN = 10;
//...
}
Then, as already stated, you can use static imports to use your constants.

My preferred method is not to do that at all. The age of constants pretty much died when Java 5 introduced typesafe enums. And even before then Josh Bloch published a (slightly more wordy) version of that, which worked on Java 1.4 (and earlier).
Unless you need interoperability with some legacy code there's really no reason to use named String/integer constants anymore.

enums are fine. IIRC, one item in effective Java (2nd Ed) has enum constants enumerating standard options implementing a [Java keyword] interface for any value.
My preference is to use a [Java keyword] interface over a final class for constants. You implicitly get the public static final. Some people will argue that an interface allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.
Which looks better?
public final class SomeStuff {
private SomeStuff() {
throw new Error();
}
public static final String SOME_CONST = "Some value or another, I don't know.";
}
Or:
public interface SomeStuff {
String SOME_CONST = "Some value or another, I don't know.";
}

Just use final class.
If you want to be able to add other values use an abstract class.
It doesn't make much sense using an interface, an interface is supposed to specify a contract. You just want to declare some constant values.

Aren't enums best choice for these kinds of stuff?

Or 4. Put them in the class that contains the logic that uses the constants the most
... sorry, couldn't resist ;-)

The best approach for me, is enum:
public enum SomeApiConstants {;
public static final String SOME_CONST = "SOME_VALUE";
//may be in hierarchy
public enum ApiMapping {;
public static final String VERSION = "/version";
public static final String VERSION_LIST = "/list/{type}";
}
}
Pros:
clean code
the private constructor does not need to be defined
attempt to instantiate is validated in compile time as java: enum types may not be instantiated
prevents to clone and deserialization

One of the disadvantage of private constructor is the exists of method could never be tested.
Enum by the nature concept good to apply in specific domain type, apply it to decentralized constants looks not good enough
The concept of Enum is "Enumerations are sets of closely related items".
Extend/implement a constant interface is a bad practice, it is hard to think about requirement to extend a immutable constant instead of referring to it directly.
If apply quality tool like SonarSource, there are rules force developer to drop constant interface, this is a awkward thing as a lot of projects enjoy the constant interface and rarely to see "extend" things happen on constant interfaces

Related

How should I manage constants in a Java project [duplicate]

I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface.
For instance, processing.org has an interface called PConstants.java, and most other core classes implement this interface. The interface is riddled with static members. Is there a reason for this approach, or is this considered bad practice? Why not use enums where it makes sense, or a static class?
I find it strange to use an interface to allow for some sort of pseudo 'global variables'.
public interface PConstants {
// LOTS OF static fields...
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
static public final int VERTEX_FIELD_COUNT = 36;
// renderers known to processing.core
static final String P2D = "processing.core.PGraphics2D";
static final String P3D = "processing.core.PGraphics3D";
static final String JAVA2D = "processing.core.PGraphicsJava2D";
static final String OPENGL = "processing.opengl.PGraphicsOpenGL";
static final String PDF = "processing.pdf.PGraphicsPDF";
static final String DXF = "processing.dxf.RawDXF";
// platform IDs for PApplet.platform
static final int OTHER = 0;
static final int WINDOWS = 1;
static final int MACOSX = 2;
static final int LINUX = 3;
static final String[] platformNames = {
"other", "windows", "macosx", "linux"
};
// and on and on
}
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
import static com.kittens.kittenpolisher.KittenConstants.*;
This avoids the ugliness of making your classes implement interfaces that have no functionality.
As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.
But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)
Eg:
/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
private KittenConstants() {}
public static final String KITTEN_SOUND = "meow";
public static final double KITTEN_CUTENESS_FACTOR = 1;
}
I do not pretend the right to be right, but lets see this small example:
public interface CarConstants {
static final String ENGINE = "mechanical";
static final String WHEEL = "round";
// ...
}
public interface ToyotaCar extends CarConstants //, ICar, ... {
void produce();
}
public interface FordCar extends CarConstants //, ICar, ... {
void produce();
}
// and this is implementation #1
public class CamryCar implements ToyotaCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
// and this is implementation #2
public class MustangCar implements FordCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...
Constants should not be changed, because the wheel is round and egine is mechanical, but...
In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface
public interface InnovativeCarConstants {
static final String ENGINE = "electronic";
static final String WHEEL = "flat";
// ...
}
and now we can change our abstraction:
public interface ToyotaCar extends CarConstants
to
public interface ToyotaCar extends InnovativeCarConstants
And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations
Its NOT SAFE, I know,
but I still want to know that do you think about this
There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:
The concepts are part of the public interface of several
classes.
Their values might change in future releases.
Its critical that all implementations use the same values.
For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.
So you write a public interface with the static constant:
public interface SyntaxExtensions {
// query type
String NEAR_TO_QUERY = "nearTo";
// params for query
String POINT = "coordinate";
String DISTANCE_KM = "distanceInKm";
}
Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.
PS: The inspiration for this example is drawn from the Neo4j spatial code.
Given the advantage of hindsight, we can see that Java is broken in many ways. One major failing of Java is the restriction of interfaces to abstract methods and static final fields. Newer, more sophisticated OO languages like Scala subsume interfaces by traits which can (and typically do) include concrete methods, which may have arity zero (constants!). For an exposition on traits as units of composable behavior, see http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. For a short description of how traits in Scala compare with interfaces in Java, see http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5. In the context of teaching OO design, simplistic rules like asserting that interfaces should never include static fields are silly. Many traits naturally include constants and these constants are appropriately part of the public "interface" supported by the trait. In writing Java code, there is no clean, elegant way to represent traits, but using static final fields within interfaces is often part of a good workaround.
According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM
By default, all the methods in interface is abstract even tough you didn't mention it explicitly.
Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.
I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.
Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.
If a client wants to compare cars prior to buying he can have a method like this:
public List<Decision> compareCars(List<I_Somecar> pCars);
An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.
This came from a time before Java 1.5 exists and bring enums to us. Prior to that, there was no good way to define a set of constants or constrained values.
This is still used, most of the time either for backward compatibility or due to the amount of refactoring needed to get rid off, in a lot of project.

Constant string substitution

I have a class of constants
public class Constants {
private static final String A = "1";
private static final String B = "2";
}
I have another class which takes in the name of the constant as a function parameter and calls the constant.
public class SomeClas {
void someMethod(String constantName) {
callSomeOtherMethod(Constants.<constantName>)
}
}
How Do i do this? My <constantName> can take values as A or B.
Assuming you cannot change anything in the way your classes look like, you are left with reflection. The code to do it with reflection is as follows:
void someMethod(String constantName) throws NoSuchFieldException, IllegalAccessException {
Field fd = Constants.class.getDeclaredField(constantName);
fd.setAccessible(true);
String val = (String) fd.get(null);
callSomeOtherMethod(val);
}
The answer depends on how much control you have of the class Constants. If this is out of your control and you cannot change it then reflection is the way to go. (see marcinj's answer)
However, if you have full control over Constants then I would consider refactoring to an enum (available since Java 5). Whether this is worthwhile will depend on how embedded this class is in your code base. How many places that reference Constants would have to change? Is this a shared class used by other applications? It could be that refactoring here is too much hassle, only you can decide.
To help you decide here is a summary of reasons why using an enum would generally be considered preferable, certainly for new development. If you decide not to refactor then it's still worth a look for the next time you need to create new constants like this.
Reasons against using reflection
Performance - runtime reflection is much slower than compiled method calls or attribute lookups. If your code is called infrequently then you probably won't notice it but if this is a utility method that is called many times then it could be a potential bottleneck.
Overriding the access modifier - private scope attributes are supposed to only be accessible from within the same class. By overriding this you can introduce problems when refactoring as your reflection code could be dependent on attributes or methods that it shouldn't know about.
Compile time safety - if you call a method or reference an attribute in the standard way the compiler will check it exists. If you look things up with reflection then you leave yourself open to runtime errors.
Reasons to prefer an enum to String/int constants
- Each constant can have attributes and methods - Using the Joshua Bloch example you might have a constants class listing the planets of the solar system. If you use an enum type then you can add attributes such as mass, radius etc and methods to retrieve them.
- Compile time type safety - With a class of String constants if you want to pass this in to a method the type will be String, not Constants. This means the compiler will be happy with any old String you pass in whether it's a Constant or not. If you use an enum you have a proper type that the compiler can check.
- You get lots for free such as name(), valueOf(), implements Serializable, Comparable etc. This means you don't have to re-invent the wheel.
- It's a thought out design - Before enums there were a number of design patterns to achieve the same thing with varying levels of considerations. For example do you worry about thread safety? Or Serialization? If you use an enum you don't have to worry about this.
Code example
If you do decide to refactor to an enum then here is an example code snippet to show how this might be achieved.
public enum Constant
{
A("1"),
B("2");
private String value;
private Constant(String value)
{
this.value = value;
}
public Constant lookupConstantByValue(String value)
{
for(Constant constant : values())
{
if(constant.value.equals(value))
{
return constant;
}
}
return null;
}
}
You could now lookup constant values either by the A,B name or the "1", "2" value. e.g.
public class SomeClas
{
void someMethod(String constantName)
{
// if constantName is 1 or 2
callSomeOtherMethod(Constant.lookupConstantByValue(constantName));
// if constantName is A or B
callSomeOtherMethod(Constant.valueOf(constantName));
}
}

Using Java Enum for BigDecimal Constants

Originally I had one class with a bunch of private static finals
private static final BigDecimal BD_0_06 = new BigDecimal("0.06");
private static final BigDecimal BD_0_08 = new BigDecimal("0.08");
private static final BigDecimal BD_0_10 = new BigDecimal("0.10");
private static final BigDecimal BD_0_12 = new BigDecimal("0.12");
private static final BigDecimal BD_0_14 = new BigDecimal("0.14");
...
and a bunch of methods in that class that used those constants
private void computeFastenerLengthToleranceMax() {
if (nominal_fastener_length.compareTo(BigDecimal.ONE) > 0 && nominal_fastener_length.compareTo(BD_TWO_AND_ONE_HALF) <= 0) {
if (spec.getBasic_major_diameter().compareTo(BD_ONE_QUARTER) >= 0 && spec.getBasic_major_diameter().compareTo(BD_THREE_EIGTHS) <= 0) {
setLength_tolerance_max(BD_0_02);
}
if (spec.getBasic_major_diameter().compareTo(BD_SEVEN_SIXTEENTHS) >= 0 && spec.getBasic_major_diameter().compareTo(BD_ONE_HALF) <= 0) {
setLength_tolerance_max(BD_0_04);
}
if (spec.getBasic_major_diameter().compareTo(BD_NINE_SIXTEENTHS) >= 0 && spec.getBasic_major_diameter().compareTo(BD_THREE_QUARTER) <= 0) {
setLength_tolerance_max(BD_0_06);
}
Now I'd like to create other similar classes that use the same constants. At first I extended a based class that contained these constants but then decided to try composition instead of inheritance because of other issues and now I'm trying to use Enum for my constants.
public enum EnumBD {
BD_0_00 (new BigDecimal("0.00")),
BD_0_02 (new BigDecimal("0.02")),
BD_0_03 (new BigDecimal("0.03")),
BD_0_04 (new BigDecimal("0.04")),
BD_0_05 (new BigDecimal("0.05")),
.....
private BigDecimal value;
private EnumBD(BigDecimal value) {
this.value = value;
}
public BigDecimal getValue() {
return value;
}
}
But in my method my reference to all my constants goes from something like this
setLength_tolerance_max(BD_0_02);
to this
setLength_tolerance_max(EnumBD.BD_0_02.getValue());
Am I off track or is this how Enum constants were intended to be used?
Now I'd like to create other similar classes that use the same
constants. At first I extended a based class that contained these
constants but then decided to try composition instead of inheritance
because of other issues and now I'm trying to use Enum for my
constants.
There are basically two ways (aside from defining your own enum class), broadly speaking, to export constants for use in multiple classes. That said, you really ought to consider whether there is a workable way to use an enum class to represent your constants since an enum class is the facility of choice to use whenever you have a set of fixed constants that are known at compile time. The following is for a case in which you have decided not to use an enum class.
Use an interface
This advice is provided with reservation. This mechanism works as a means to export constants, but it is regarded by coding experts as an antipattern and not one to be emulated, most especially in an API that you exporting.
Nevertheless it is true that if you define static final constants in an interface, any class that implements that interface (and any subclass of that class) will be able to use your constants by their unqualified names. An interface that defines ONLY constants in this way is called a constant interface. There are a few examples of constant interfaces in the Java Platform Libraries.
The reasons not to use constant interfaces are many and have been discussed elsewhere ... however they can be convenient to use. Use constant interfaces at your own prerogative and be aware that they have some potential to cause problems (namespace pollution, programmer confusion, etc).
Use a class
Define your constants as public, final, and static in an ordinary class. They should very likely also be primitive or immutable types. Your class can then export these constants to any other class that can make use of them.
This is preferred over exporting constants with a constant interface because interfaces should really only be used to define types and APIs. Non-instantiable "constant classes" are a perfectly acceptable use of the class mechanism. This is especially true if the constants are thematically related. For example, say you wish to define constants representing various boiling points:
public class BoilingPoints {
public static final double WATER = 100.0;
:
:
public static final double ETHANOL = 86.2;
private BoilingPoints() { throw new AssertionError(); }
}
Note that the constructor assures that the class is non-instantiable.
The main downside is that you ordinarily must qualify constants exported from a class with the class name. Since the static import mechanism was added to the language, you don't -have- to do that if you don't wish to.
You want to use a constant when you want readability and convenience, so for instance
static final double PI = 3.1415;
lets you write something like
c = 2 * PI * r;
making the intent clear. An enum is useful when you want to ensure your values are from a pre-defined set and the check to be done at compile time. Suppose I wanted write a class modeling something like a traffic light. I can define an enum for its states, STOP, CAUTION and GO. That way, I can ensure at compile time, that any setting of the state of my light would be one of these three states. If I defined integer constants for these, there is nothing stopping someone from not using my constants and simply setting the state to 139.
The ability to associate values with my Enum elements is an additional convenience, in my traffic light case, I could associate an RGB value with each for display purposes, for instance.
In your case, it seems reasonably clear constants will do and enums just complicate your code.
Seems like the enum would give you ability to move the key value pairs out to another structure which cleans up the class that utilizes this composition. This can also be achieved by creating a class that has public properties like BD_0_00... Enum really doesn't buy you much over that implementation.
Would not use enum in this case, unless there is more data comming down the road describing the values.
A prefered way of doing things would be to make them global, I.E. public static final. Since BigDecimal is immutable, you do not have to worry about the general "no global state" rule. They basically become constants.

When to use static fields and when to use enumerations? [duplicate]

I am very familiar with C# but starting to work more in Java. I expected to learn that enums in Java were basically equivalent to those in C# but apparently this is not the case. Initially I was excited to learn that Java enums could contain multiple pieces of data which seems very advantageous (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). However, since then I have found a lot of features missing that are trivial in C#, such as the ability to easily assign an enum element a certain value, and consequently the ability to convert an integer to an enum without a decent amount of effort (i.e. Convert integer value to matching Java Enum).
So my question is this: is there any benefit to Java enums over a class with a bunch of public static final fields? Or does it just provide more compact syntax?
EDIT: Let me be more clear. What is the benefit of Java enums over a class with a bunch of public static final fields of the same type? For example, in the planets example at the first link, what is the advantage of an enum over a class with these public constants:
public static final Planet MERCURY = new Planet(3.303e+23, 2.4397e6);
public static final Planet VENUS = new Planet(4.869e+24, 6.0518e6);
public static final Planet EARTH = new Planet(5.976e+24, 6.37814e6);
public static final Planet MARS = new Planet(6.421e+23, 3.3972e6);
public static final Planet JUPITER = new Planet(1.9e+27, 7.1492e7);
public static final Planet SATURN = new Planet(5.688e+26, 6.0268e7);
public static final Planet URANUS = new Planet(8.686e+25, 2.5559e7);
public static final Planet NEPTUNE = new Planet(1.024e+26, 2.4746e7);
As far as I can tell, casablanca's answer is the only one that satisfies this.
Type safety and value safety.
Guaranteed singleton.
Ability to define and override methods.
Ability to use values in switch statement case statements without qualification.
Built-in sequentialization of values via ordinal().
Serialization by name not by value, which offers a degree of future-proofing.
EnumSet and EnumMap classes.
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.
Nobody mentioned the ability to use them in switch statements; I'll throw that in as well.
This allows arbitrarily complex enums to be used in a clean way without using instanceof, potentially confusing if sequences, or non-string/int switching values. The canonical example is a state machine.
The primary advantage is type safety. With a set of constants, any value of the same intrinsic type could be used, introducing errors. With an enum only the applicable values can be used.
For example
public static final int SIZE_SMALL = 1;
public static final int SIZE_MEDIUM = 2;
public static final int SIZE_LARGE = 3;
public void setSize(int newSize) { ... }
obj.setSize(15); // Compiles but likely to fail later
vs
public enum Size { SMALL, MEDIUM, LARGE };
public void setSize(Size s) { ... }
obj.setSize( ? ); // Can't even express the above example with an enum
There is less confusion. Take Font for instance. It has a constructor that takes the name of the Font you want, its size and its style (new Font(String, int, int)). To this day I cannot remember if style or size goes first. If Font had used an enum for all of its different styles (PLAIN, BOLD, ITALIC, BOLD_ITALIC), its constructor would look like Font(String, Style, int), preventing any confusion. Unfortunately, enums weren't around when the Font class was created, and since Java has to maintain reverse compatibility, we will always be plagued by this ambiguity.
Of course, this is just an argument for using an enum instead of public static final constants. Enums are also perfect for singletons and implementing default behavior while allowing for later customization (I.E. the strategy pattern). An example of the latter is java.nio.file's OpenOption and StandardOpenOption: if a developer wanted to create his own non-standard OpenOption, he could.
There are many good answers here, but none mentiones that there are highly optimized implementations of the Collection API classes/interfaces specifically for enums:
EnumSet
EnumMap
These enum specific classes only accept Enum instances (the EnumMap only accept Enums only as keys), and whenever possible, they revert to compact representation and bit manipulation in their implementation.
What does this mean?
If our Enum type has no more that 64 elements (most of real-life Enum examples will qualify for this), the implementations store the elements in a single long value, each Enum instance in question will be associated with a bit of this 64-bit long long. Adding an element to an EnumSet is simply just setting the proper bit to 1, removing it is just setting that bit to 0. Testing if an element is in the Set is just one bitmask test! Now you gotta love Enums for this!
example:
public class CurrencyDenom {
public static final int PENNY = 1;
public static final int NICKLE = 5;
public static final int DIME = 10;
public static final int QUARTER = 25;}
Limitation of java Constants
1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to int e.g. 99 though there is no coin to represent that value.
2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"
3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5
Advantage of enum
1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error
2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.
3) You can specify values of enum constants at the creation time as shown in below example:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
private Currency(int value) {
this.value = value;
}
};
Reference: https://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html
The first benefit of enums, as you have already noticed, is syntax simplicity. But the main point of enums is to provide a well-known set of constants which, by default, form a range and help to perform more comprehensive code analysis through type & value safety checks.
Those attributes of enums help both a programmer and a compiler. For example, let's say you see a function that accepts an integer. What that integer could mean? What kind of values can you pass in? You don't really know right away. But if you see a function that accepts enum, you know very well all possible values you can pass in.
For the compiler, enums help to determine a range of values and unless you assign special values to enum members, they are well ranges from 0 and up. This helps to automatically track down errors in the code through type safety checks and more. For example, compiler may warn you that you don't handle all possible enum values in your switch statement (i.e. when you don't have default case and handle only one out of N enum values). It also warns you when you convert an arbitrary integer into enum because enum's range of values is less than integer's and that in turn may trigger errors in the function that doesn't really accept an integer. Also, generating a jump table for the switch becomes easier when values are from 0 and up.
This is not only true for Java, but for other languages with a strict type-checking as well. C, C++, D, C# are good examples.
An enum is implictly final, with a private constructors, all its values are of the same type or a sub-type, you can obtain all its values using values(), gets its name() or ordinal() value or you can look up an enum by number or name.
You can also define subclasses (even though notionally final, something you can't do any other way)
enum Runner implements Runnable {
HI {
public void run() {
System.out.println("Hello");
}
}, BYE {
public void run() {
System.out.println("Sayonara");
}
public String toString() {
return "good-bye";
}
}
}
class MYRunner extends Runner // won't compile.
enum Benefits:
Enums are type-safe, static fields are not
There is a finite number of values (it is not possible to pass non-existing enum value. If you have static class fields, you can make that mistake)
Each enum can have multiple properties (fields/getters) assigned - encapsulation. Also some simple methods: YEAR.toSeconds() or similar. Compare: Colors.RED.getHex() with Colors.toHex(Colors.RED)
"such as the ability to easily assign an enum element a certain value"
enum EnumX{
VAL_1(1),
VAL_200(200);
public final int certainValue;
private X(int certainValue){this.certainValue = certainValue;}
}
"and consequently the ability to convert an integer to an enum without a decent amount of effort"
Add a method converting int to enum which does that. Just add static HashMap<Integer, EnumX> containing the mapping.
If you really want to convert ord=VAL_200.ordinal() back to val_200 just use: EnumX.values()[ord]
You get compile time checking of valid values when you use an enum. Look at this question.
The biggest advantage is enum Singletons are easy to write and thread-safe :
public enum EasySingleton{
INSTANCE;
}
and
/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
private volatile DoubleCheckedLockingSingleton INSTANCE;
private DoubleCheckedLockingSingleton(){}
public DoubleCheckedLockingSingleton getInstance(){
if(INSTANCE == null){
synchronized(DoubleCheckedLockingSingleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
both are similar and it handled Serialization by themselves by implementing
//readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
more
Another important difference is that java compiler treats static final fields of primitive types and String as literals. It means these constants become inline. It's similar to C/C++ #define preprocessor. See this SO question. This is not the case with enums.
Enums can be local
As of Java 16, an enum can be defined locally (within a method). This scope is in addition to being able to define an enum as nested or as separate class.
This new local definition scope came along with the new records feature. See JEP 395: Records for details. Enums, interfaces, and records can all be defined locally in Java 16+.
In contrast, public static final fields always have global scope.
I think an enum can't be final, because under the hood compiler generates subclasses for each enum entry.
More information From source
There are many advantages of enums that are posted here, and I am creating such enums right now as asked in the question.
But I have an enum with 5-6 fields.
enum Planet{
EARTH(1000000, 312312321,31232131, "some text", "", 12),
....
other planets
....
In these kinds of cases, when you have multiple fields in enums, it is much difficult to understand which value belongs to which field as you need to see constructor and eye-ball.
Class with static final constants and using Builder pattern to create such objects makes it more readable. But, you would lose all other advantages of using an enum, if you need them.
One disadvantage of such classes is, you need to add the Planet objects manually to the list/set of Planets.
I still prefer enum over such class, as values() comes in handy and you never know if you need them to use in switch or EnumSet or EnumMap in future :)
Main reason: Enums help you to write well-structured code where the semantic meaning of parameters is clear and strongly-typed at compile time - for all the reasons other answers have given.
Quid pro quo: in Java out of the box, an Enum's array of members is final. That's normally good as it helps value safety and testing, but in some situations it could be a drawback, for example if you are extending existing base code perhaps from a library. In contrast, if the same data is in a class with static fields you can easily add new instances of that class at runtime (you might also need to write code to add these to any Iterable you have for that class). But this behaviour of Enums can be changed: using reflection you can add new members at runtime or replace existing members, though this should probably only be done in specialised situations where there is no alternative: i.e. it's a hacky solution and may produce unexpected issues, see my answer on Can I add and remove elements of enumeration at runtime in Java.
You can do :
public enum Size { SMALL(1), MEDIUM(2), LARGE(3) };
private int sizeValue;
Size(sizeValue) {this.sizeValue = value; }
So with this you can get size value like this SMALL.getSizeValue();
If you want to set sizes Enums are not for you, if you will be only define constants and fixed values are fine.
Check this link maybe can help you

Why can't a class extend an enum?

I am wondering why in the Java language a class cannot extend an enum.
I'm not talking about an enum extending an enum (which can't be done, since java doesn't have multiple inheritance, and that enums implicitly extend java.lang.Enum), but a class that extends an enum in order to only add extra methods, not extra enumeration values.
Something like:
enum MyEnum
{
ASD(5),
QWE(3),
ZXC(7);
private int number;
private asd(int number)
{
this.number=number;
}
public int myMethod()
{
return this.number;
}
}
class MyClass extends MyEnum
{
public int anotherMethod()
{
return this.myMethod()+1;
}
}
To be used like this:
System.out.println(MyClass.ASD.anotherMethod());
So, can anyone provide a rationale (or point me to the right JLS section) for this limitation?
You can't extend an enum. They are implicitly final. From JLS § 8.9:
An enum type is implicitly final unless it contains at least one enum constant that has a class body.
Also, from JLS §8.1.4 - Superclasses and Subclasses:
It is a compile-time error if the ClassType names the class Enum or any invocation of it.
Basically an enum is an enumerated set of pre-defined constants. Due to this, the language allows you to use enums in switch-cases. By allowing to extend them, wouldn't make them eligible type for switch-cases, for example. Apart from that, an instance of the class or other enum extending the enum would be then also be an instance of the enum you extend. That breaks the purpose of enums basically.
In ancient days of pre Java 1.5 you would probably do enums like this:
public class MyEnum {
public static final MyEnum ASD = new MyEnum(5);
public static final MyEnum QWE = new MyEnum(3);
public static final MyEnum ZXC = new MyEnum(7);
private int number;
private MyEnum(int number) {
this.number = number;
}
public int myMethod() {
return this.number;
}
}
There are two important things about this figure:
private constructor that will not allow to instantiate the class from outside
actual "enum" values are stored in static fields
Even if it's not final when you'll extend it, you'll realize that compiler requires an explicit constructor, that in other turn is required to call super constructor which is impossible since that one is private. Another problem is that the static fields in super class still store object of that super class not your extending one. I think that this could be an explanation.
The whole point of an enum is to create a closed set of possible values. This makes it easier to reason about what a value of that enum type is -- easier for you the programmer, and also easier for the compiler (this closedness is what lets it handle enums efficiently in switches, for instance). Allowing a class to extend an enum would open up the set of possible values; at that point, what does the enum buy you that a regular class wouldn't?
I think an answer to why they did it this way comes from this question:
In your example, how would you instantiate a MyClass? Enums are never explicitly instantiated (via a new MyEnum()) by the user. You'd have to do something like MyClass.ASD but not sure how that would work.
Basically, I don't know what syntax would work for your proposed addition. Which is probably why they made them final etc...
EDIT ADDED
If the author of the original Enum planned ahead (unlikely), and you are not worried too much abut thread safety, you could do something like this: (BTW, I'd probably scream at anybody who actually did this in production code, YMMV)
public enum ExtendibleEnum {
FOO, BAR, ZXC;
private Runnable anotherMethodRunme; // exact Interface will vary, I picked an easy one
// this is what gets "injected" by your other class
public void setAnotherMethodRunMe(Runnable r) { // inject here
anotherMethodRunme= r;
}
public void anotherMethod() { // and this behavior gets changed
anotherMethodRunme.run();
}
}
May I also add that we can emulate Extensible enums using interfaces.
From Joshua Bloch's brilliant book
http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA165&lpg=PA165&dq=mulate+extensible+enums+with+interfaces&source=bl&ots=yYKhIho1R0&sig=vd6xgrOcKr4Xhb6JDAdkxLO278A&hl=en&sa=X&ei=XyBgUqLVD8-v4APE6YGABg&ved=0CDAQ6AEwAQ#v=onepage&q=mulate%20extensible%20enums%20with%20interfaces&f=false
or
http://jtechies.blogspot.com/2012/07/item-34-emulate-extensible-enums-with.html
The whole point of an enum is to create a closed set of possible values. This makes it easier to reason about what a value of that enum type is so the set of constants would still remain closed and unextended, but then again the enum would carry the extra methods provided by the extending class.

Categories

Resources