Are java enum variables static? [duplicate] - java

This question already has answers here:
In Java, are enum types inside a class static?
(2 answers)
Closed 7 years ago.
public enum Operations {
SINGLE,
MULTIPLE;
private Type operation;
public void setOperation(Type operation) {
this.operation = operation;
}
public Type getOperation() {
return operation;
}
public static void main(String[] args) {
Operations oper1 = Operations.SINGLE;
oper1.setOperation(Type.GET);
Operations oper2 = Operations.SINGLE;
oper2.setOperation(Type.POST);
System.out.println(oper1.getOperation());
System.out.println(oper2.getOperation());
}
}
enum Type {
POST,
GET;
}
In the above code, the value of operation changes for both the Operations. How can I have two instances of Operations.SINGLE with different operation type?

Yes, instances are implicitly static and final. This means that the code is unwise. Imagine two threads both calling SINGLE.setOperation(Type); you will have no confidence in what you are calling.
From the Java Language Specification, Section 8.9:
Enum types (§8.9) must not be declared abstract; doing so will result in a compile-time error.
An enum type is implicitly final unless it contains at least one enum constant that has a class body.
It is a compile-time error to explicitly declare an enum type to be final.
Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.
And in the next section:
The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type.
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

How can I have two instances of Operations.SINGLE with different operation type?
The fundamental idea behind an enum is that there is one, and only one, instance of each of its members. This is what lets you safely compare them for equality, without fear that there's another SINGLE or MULTIPLE created in some other place.
If you want multiple instances of SINGLE, make it a class, not an enum. The fact that you made your enum mutable indirectly points in the same direction: using enum is a wrong choice in your situation.

Enum instances are "static" (ie behave like static variables), but are not immutable.
All threads see the same object referred to by the enum name - they are like singletons, with an iron-clad guarantee from the JVM that there is only ever one instance of an enum. Changing a field of an enum changes it for everyone.
It is good practice to make your fields final in an enum and to make them immutable.

I'm one year and a half too late. But I see the question was not really answered.
The solution would be using a class instead of enum, that has those two enums as its fields:
class Operation {
Quantity quantity;
Type type;
Operation(Quantity quantity, Type type) {
this.quantity = quantity;
this.type = type;
}
}
You can, of course, use enum instead of class. Then you'll have to enumerate all combinations:
enum Operation {
SINGLE_GET(Quantity.SINGLE, Type.GET)
SINGLE_POST(Quantity.SINGLE, Type.POST)
MULTIPLE_GET(Quantity.MULTIPLE, Type.GET)
// ... more options
// contents same as in class Operation, constructor private by default
}
Both approaches are valid, sometimes you really want to enumerate all the combinations, most of the time, however, you should probably stick with the class approach.
For brevity, I didn't define the enums Quantity and Type, they are just simple enums.

Yes, all elements of enum are static final constant.
However as mentioned in another answer by darijan, there is a logical mistake in your program.

There is an error in fourth line of main method
oper1.setOperation(Type.POST);
should be
oper2.setOperation(Type.POST);

Related

get or set a class value as strings [duplicate]

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread-safety benefits to such solution.
I have never used enums and I have been programming in Java for more than a couple of years now. And apparently, they changed a lot. Now they even do full-blown support of OOP within themselves.
Now why and what should I use enum in day to day programming?
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").
If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
BTW, overuse of enums might mean that your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go.
As an example, which is better?
/** Counts number of foobangs.
* #param type Type of foobangs to count. Can be 1=green foobangs,
* 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
* #return number of foobangs of type
*/
public int countFoobangs(int type)
versus
/** Types of foobangs. */
public enum FB_TYPE {
GREEN, WRINKLED, SWEET,
/** special type for all types combined */
ALL;
}
/** Counts number of foobangs.
* #param type Type of foobangs to count
* #return number of foobangs of type
*/
public int countFoobangs(FB_TYPE type)
A method call like:
int sweetFoobangCount = countFoobangs(3);
then becomes:
int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);
In the second example, it's immediately clear which types are allowed, docs and implementation cannot go out of sync, and the compiler can enforce this.
Also, an invalid call like
int sweetFoobangCount = countFoobangs(99);
is no longer possible.
Why use any programming language feature? The reason we have languages at all is for
Programmers to efficiently and correctly express algorithms in a form computers can use.
Maintainers to understand algorithms others have written and correctly make changes.
Enums improve both likelihood of correctness and readability without writing a lot of boilerplate. If you are willing to write boilerplate, then you can "simulate" enums:
public class Color {
private Color() {} // Prevent others from making colors.
public static final Color RED = new Color();
public static final Color AMBER = new Color();
public static final Color GREEN = new Color();
}
Now you can write:
Color trafficLightColor = Color.RED;
The boilerplate above has much the same effect as
public enum Color { RED, AMBER, GREEN };
Both provide the same level of checking help from the compiler. Boilerplate is just more typing. But saving a lot of typing makes the programmer more efficient (see 1), so it's a worthwhile feature.
It's worthwhile for at least one more reason, too:
Switch statements
One thing that the static final enum simulation above does not give you is nice switch cases. For enum types, the Java switch uses the type of its variable to infer the scope of enum cases, so for the enum Color above you merely need to say:
Color color = ... ;
switch (color) {
case RED:
...
break;
}
Note it's not Color.RED in the cases. If you don't use enum, the only way to use named quantities with switch is something like:
public Class Color {
public static final int RED = 0;
public static final int AMBER = 1;
public static final int GREEN = 2;
}
But now a variable to hold a color must have type int. The nice compiler checking of the enum and the static final simulation is gone. Not happy.
A compromise is to use a scalar-valued member in the simulation:
public class Color {
public static final int RED_TAG = 1;
public static final int AMBER_TAG = 2;
public static final int GREEN_TAG = 3;
public final int tag;
private Color(int tag) { this.tag = tag; }
public static final Color RED = new Color(RED_TAG);
public static final Color AMBER = new Color(AMBER_TAG);
public static final Color GREEN = new Color(GREEN_TAG);
}
Now:
Color color = ... ;
switch (color.tag) {
case Color.RED_TAG:
...
break;
}
But note, even more boilerplate!
Using an enum as a singleton
From the boilerplate above you can see why an enum provides a way to implement a singleton. Instead of writing:
public class SingletonClass {
public static final void INSTANCE = new SingletonClass();
private SingletonClass() {}
// all the methods and instance data for the class here
}
and then accessing it with
SingletonClass.INSTANCE
we can just say
public enum SingletonClass {
INSTANCE;
// all the methods and instance data for the class here
}
which gives us the same thing. We can get away with this because Java enums are implemented as full classes with only a little syntactic sugar sprinkled over the top. This is again less boilerplate, but it's non-obvious unless the idiom is familiar to you. I also dislike the fact that you get the various enum functions even though they don't make much sense for the singleton: ord and values, etc. (There's actually a trickier simulation where Color extends Integer that will work with switch, but it's so tricky that it even more clearly shows why enum is a better idea.)
Thread safety
Thread safety is a potential problem only when singletons are created lazily with no locking.
public class SingletonClass {
private static SingletonClass INSTANCE;
private SingletonClass() {}
public SingletonClass getInstance() {
if (INSTANCE == null) INSTANCE = new SingletonClass();
return INSTANCE;
}
// all the methods and instance data for the class here
}
If many threads call getInstance simultaneously while INSTANCE is still null, any number of instances can be created. This is bad. The only solution is to add synchronized access to protect the variable INSTANCE.
However, the static final code above does not have this problem. It creates the instance eagerly at class load time. Class loading is synchronized.
The enum singleton is effectively lazy because it's not initialized until first use. Java initialization is also synchronized, so multiple threads can't initialize more than one instance of INSTANCE. You're getting a lazily initialized singleton with very little code. The only negative is the the rather obscure syntax. You need to know the idiom or thoroughly understand how class loading and initialization work to know what's happening.
Besides the already mentioned use-cases, I often find enums useful for implementing the strategy pattern, following some basic OOP guidelines:
Having the code where the data is (that is, within the enum itself -- or often within the enum constants, which may override methods).
Implementing an interface (or more) in order to not bind the client code to the enum (which should only provide a set of default implementations).
The simplest example would be a set of Comparator implementations:
enum StringComparator implements Comparator<String> {
NATURAL {
#Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
},
REVERSE {
#Override
public int compare(String s1, String s2) {
return NATURAL.compare(s2, s1);
}
},
LENGTH {
#Override
public int compare(String s1, String s2) {
return new Integer(s1.length()).compareTo(s2.length());
}
};
}
This "pattern" can be used in far more complex scenarios, making extensive use of all the goodies that come with the enum: iterating over the instances, relying on their implicit order, retrieving an instance by its name, static methods providing the right instance for specific contexts etc. And still you have this all hidden behind the interface so your code will work with custom implementations without modification in case you want something that's not available among the "default options".
I've seen this successfully applied for modeling the concept of time granularity (daily, weekly, etc.) where all the logic was encapsulated in an enum (choosing the right granularity for a given time range, specific behavior bound to each granularity as constant methods etc.). And still, the Granularity as seen by the service layer was simply an interface.
Something none of the other answers have covered that make enums particularly powerful are the ability to have template methods. Methods can be part of the base enum and overridden by each type. And, with the behavior attached to the enum, it often eliminates the need for if-else constructs or switch statements as this blog post demonstrates - where enum.method() does what originally would be executed inside the conditional. The same example also shows the use of static imports with enums as well producing much cleaner DSL like code.
Some other interesting qualities include the fact that enums provide implementation for equals(), toString() and hashCode() and implement Serializable and Comparable.
For a complete rundown of all that enums have to offer I highly recommend Bruce Eckel's Thinking in Java 4th edition which devotes an entire chapter to the topic. Particularly illuminating are the examples involving a Rock, Paper, Scissors (i.e. RoShamBo) game as enums.
From Java documents -
You should use enum types any time you
need to represent a fixed set of
constants. That includes natural enum
types such as the planets in our solar
system and data sets where you know
all possible values at compile
time—for example, the choices on a
menu, command line flags, and so on.
A common example is to replace a class with a set of private static final int constants (within reasonable number of constants) with an enum type. Basically if you think you know all possible values of "something" at compile time you can represent that as an enum type. Enums provide readability and flexibility over a class with constants.
Few other advantages that I can think of enum types. They is always one instance of a particular enum class (hence the concept of using enums as singleton arrives). Another advantage is you can use enums as a type in switch-case statement. Also you can use toString() on the enum to print them as readable strings.
Now why and what for should I used
enum in day to day programming?
You can use an Enum to represent a smallish fixed set of constants or an internal class mode while increasing readability. Also, Enums can enforce a certain rigidity when used in method parameters. They offer the interesting possibility of passing information to a constructor like in the Planets example on Oracle's site and, as you've discovered, also allow a simple way to create a singleton pattern.
ex: Locale.setDefault(Locale.US) reads better than Locale.setDefault(1) and enforces the use of the fixed set of values shown in an IDE when you add the . separator instead of all integers.
Enums enumerate a fixed set of values, in a self-documenting way.
They make your code more explicit, and also less error-prone.
Why not using String, or int, instead of Enum, for constants?
The compiler won't allow typos, neither values out of the fixed
set, as enums are types by themselves. Consequences:
You won't have to write a pre-condition (or a manual if) to assure your argument is in the valid range.
The type invariant comes for free.
Enums can have behaviour, just as any other class.
You would probably need a similar amount of memory to use Strings, anyway (this depends on the complexity of the Enum).
Moreover, each of the Enum's instances is a class, for which you can define its individual behaviour.
Plus, they assure thread safety upon creation of the instances (when the enum is loaded), which has seen great application in simplifying the Singleton Pattern.
This blog illustrates some of its applications, such as a State Machine for a parser.
enum means enumeration i.e. mention (a number of things) one by one.
An enum is a data type that contains fixed set of constants.
OR
An enum is just like a class, with a fixed set of instances known at compile time.
For example:
public class EnumExample {
interface SeasonInt {
String seasonDuration();
}
private enum Season implements SeasonInt {
// except the enum constants remaining code looks same as class
// enum constants are implicitly public static final we have used all caps to specify them like Constants in Java
WINTER(88, "DEC - FEB"), SPRING(92, "MAR - JUN"), SUMMER(91, "JUN - AUG"), FALL(90, "SEP - NOV");
private int days;
private String months;
Season(int days, String months) { // note: constructor is by default private
this.days = days;
this.months = months;
}
#Override
public String seasonDuration() {
return this+" -> "+this.days + "days, " + this.months+" months";
}
}
public static void main(String[] args) {
System.out.println(Season.SPRING.seasonDuration());
for (Season season : Season.values()){
System.out.println(season.seasonDuration());
}
}
}
Advantages of enum:
enum improves type safety at compile-time checking to avoid errors at run-time.
enum can be easily used in switch
enum can be traversed
enum can have fields, constructors and methods
enum may implement many interfaces but cannot extend any class because it internally extends Enum class
for more
It is useful to know that enums are just like the other classes with Constant fields and a private constructor.
For example,
public enum Weekday
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
The compiler compiles it as follows;
class Weekday extends Enum
{
public static final Weekday MONDAY = new Weekday( "MONDAY", 0 );
public static final Weekday TUESDAY = new Weekday( "TUESDAY ", 1 );
public static final Weekday WEDNESDAY= new Weekday( "WEDNESDAY", 2 );
public static final Weekday THURSDAY= new Weekday( "THURSDAY", 3 );
public static final Weekday FRIDAY= new Weekday( "FRIDAY", 4 );
public static final Weekday SATURDAY= new Weekday( "SATURDAY", 5 );
public static final Weekday SUNDAY= new Weekday( "SUNDAY", 6 );
private Weekday( String s, int i )
{
super( s, i );
}
// other methods...
}
What is an enum
enum is a keyword defined for Enumeration a new data type. Typesafe enumerations should be used liberally. In particular, they are a robust alternative to the simple String or int constants used in much older APIs to represent sets of related items.
Why to use enum
enums are implicitly final subclasses of java.lang.Enum
if an enum is a member of a class, it's implicitly static
new can never be used with an enum, even within the enum type itself
name and valueOf simply use the text of the enum constants, while toString may be overridden to provide any content, if desired
for enum constants, equals and == amount to the same thing, and can be used interchangeably
enum constants are implicitly public static final
Note
enums cannot extend any class.
An enum cannot be a superclass.
the order of appearance of enum constants is called their "natural order", and defines the order used by other items as well: compareTo, iteration order of values, EnumSet, EnumSet.range.
An enumeration can have constructors, static and instance blocks, variables, and methods but cannot have abstract methods.
Apart from all said by others.. In an older project that I used to work for, a lot of communication between entities(independent applications) was using integers which represented a small set. It was useful to declare the set as enum with static methods to get enum object from value and viceversa. The code looked cleaner, switch case usability and easier writing to logs.
enum ProtocolType {
TCP_IP (1, "Transmission Control Protocol"),
IP (2, "Internet Protocol"),
UDP (3, "User Datagram Protocol");
public int code;
public String name;
private ProtocolType(int code, String name) {
this.code = code;
this.name = name;
}
public static ProtocolType fromInt(int code) {
switch(code) {
case 1:
return TCP_IP;
case 2:
return IP;
case 3:
return UDP;
}
// we had some exception handling for this
// as the contract for these was between 2 independent applications
// liable to change between versions (mostly adding new stuff)
// but keeping it simple here.
return null;
}
}
Create enum object from received values (e.g. 1,2) using ProtocolType.fromInt(2)
Write to logs using myEnumObj.name
Hope this helps.
Enum inherits all the methods of Object class and abstract class Enum. So you can use it's methods for reflection, multithreading, serilization, comparable, etc. If you just declare a static constant instead of Enum, you can't. Besides that, the value of Enum can be passed to DAO layer as well.
Here's an example program to demonstrate.
public enum State {
Start("1"),
Wait("1"),
Notify("2"),
NotifyAll("3"),
Run("4"),
SystemInatilize("5"),
VendorInatilize("6"),
test,
FrameworkInatilize("7");
public static State getState(String value) {
return State.Wait;
}
private String value;
State test;
private State(String value) {
this.value = value;
}
private State() {
}
public String getValue() {
return value;
}
public void setCurrentState(State currentState) {
test = currentState;
}
public boolean isNotify() {
return this.equals(Notify);
}
}
public class EnumTest {
State test;
public void setCurrentState(State currentState) {
test = currentState;
}
public State getCurrentState() {
return test;
}
public static void main(String[] args) {
System.out.println(State.test);
System.out.println(State.FrameworkInatilize);
EnumTest test=new EnumTest();
test.setCurrentState(State.Notify);
test. stateSwitch();
}
public void stateSwitch() {
switch (getCurrentState()) {
case Notify:
System.out.println("Notify");
System.out.println(test.isNotify());
break;
default:
break;
}
}
}
Use enums for TYPE SAFETY, this is a language feature so you will usually get:
Compiler support (immediately see type issues)
Tool support in IDEs (auto-completion in switch case, missing cases, force default, ...)
In some cases enum performance is also great (EnumSet, typesafe alternative to traditional int-based "bit flags.")
Enums can have methods, constructors, you can even use enums inside enums and combine enums with interfaces.
Think of enums as types to replace a well defined set of int constants (which Java 'inherited' from C/C++) and in some cases to replace bit flags.
The book Effective Java 2nd Edition has a whole chapter about them and goes into more details. Also see this Stack Overflow post.
ENum stands for "Enumerated Type". It is a data type having a fixed set of constants which you define yourself.
In my opinion, all the answers you got up to now are valid, but in my experience, I would express it in a few words:
Use enums if you want the compiler to check the validity of the value of an identifier.
Otherwise, you can use strings as you always did (probably you defined some "conventions" for your application) and you will be very flexible... but you will not get 100% security against typos on your strings and you will realize them only in runtime.
Java lets you restrict variable to having one of only a few predefined values - in other words, one value from an enumerated list.
Using enums can help to reduce bug's in your code.
Here is an example of enums outside a class:
enums coffeesize{BIG , HUGE , OVERWHELMING };
//This semicolon is optional.
This restricts coffeesize to having either: BIG , HUGE , or OVERWHELMING as a variable.
In my experience I have seen Enum usage sometimes cause systems to be very difficult to change. If you are using an Enum for a set of domain-specific values that change frequently, and it has a lot of other classes and components that depend on it, you might want to consider not using an Enum.
For example, a trading system that uses an Enum for markets/exchanges. There are a lot of markets out there and it's almost certain that there will be a lot of sub-systems that need to access this list of markets. Every time you want a new market to be added to your system, or if you want to remove a market, it's possible that everything under the sun will have to be rebuilt and released.
A better example would be something like a product category type. Let's say your software manages inventory for a department store. There are a lot of product categories, and many reasons why this list of categories could change. Managers may want to stock a new product line, get rid of other product lines, and possibly reorganize the categories from time to time. If you have to rebuild and redeploy all of your systems simply because users want to add a product category, then you've taken something that should be simple and fast (adding a category) and made it very difficult and slow.
Bottom line, Enums are good if the data you are representing is very static over time and has a limited number of dependencies. But if the data changes a lot and has a lot of dependencies, then you need something dynamic that isn't checked at compile time (like a database table).
Enum? Why should it be used? I think it's more understood when you will use it. I have the same experience.
Say you have a create, delete, edit and read database operation.
Now if you create an enum as an operation:
public enum operation {
create("1")
delete("2")
edit("3")
read("4")
// You may have is methods here
public boolean isCreate() {
return this.equals(create);
}
// More methods like the above can be written
}
Now, you may declare something like:
private operation currentOperation;
// And assign the value for it
currentOperation = operation.create
So you can use it in many ways. It's always good to have enum for specific things as the database operation in the above example can be controlled by checking the currentOperation. Perhaps one can say this can be accomplished with variables and integer values too. But I believe Enum is a safer and a programmer's way.
Another thing: I think every programmer loves boolean, don't we? Because it can store only two values, two specific values. So Enum can be thought of as having the same type of facilities where a user will define how many and what type of value it will store, just in a slightly different way. :)
So far, I have never needed to use enums. I have been reading about them since they were introduced in 1.5 or version tiger as it was called back in the day. They never really solved a 'problem' for me. For those who use it (and I see a lot of them do), am sure it definitely serves some purpose. Just my 2 quid.
There are many answers here, just want to point two specific ones:
1) Using as constants in Switch-case statement.
Switch case won't allow you to use String objects for case. Enums come in handy. More: http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/
2) Implementing Singleton Design Pattern - Enum again, comes to rescue. Usage, here: What is the best approach for using an Enum as a singleton in Java?
What gave me the Ah-Ha moment was this realization: that Enum has a private constructor only accessible via the public enumeration:
enum RGB {
RED("Red"), GREEN("Green"), BLUE("Blue");
public static final String PREFIX = "color ";
public String getRGBString() {
return PREFIX + color;
}
String color;
RGB(String color) {
this.color = color;
}
}
public class HelloWorld {
public static void main(String[] args) {
String c = RGB.RED.getRGBString();
System.out.print("Hello " + c);
}
}
As for me to make the code readable in future the most useful aplyable case of enumeration is represented in next snippet:
public enum Items {
MESSAGES, CHATS, CITY_ONLINE, FRIENDS, PROFILE, SETTINGS, PEOPLE_SEARCH, CREATE_CHAT
}
#Override
public boolean onCreateOptionsMenu(Menu menuPrm) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menuPrm);
View itemChooserLcl;
for (int i = 0; i < menuPrm.size(); i++) {
MenuItem itemLcl = menuPrm.getItem(i);
itemChooserLcl = itemLcl.getActionView();
if (itemChooserLcl != null) {
//here Im marking each View' tag by enume values:
itemChooserLcl.setTag(Items.values()[i]);
itemChooserLcl.setOnClickListener(drawerMenuListener);
}
}
return true;
}
private View.OnClickListener drawerMenuListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
Items tagLcl= (Items) v.getTag();
switch (tagLcl){
case MESSAGES: ;
break;
case CHATS : ;
break;
case CITY_ONLINE : ;
break;
case FRIENDS : ;
break;
case PROFILE: ;
break;
case SETTINGS: ;
break;
case PEOPLE_SEARCH: ;
break;
case CREATE_CHAT: ;
break;
}
}
};
In addition to #BradB Answer :
That is so true... It's strange that it is the only answer who mention that. When beginners discover enums, they quickly take that as a magic-trick for valid identifier checking for the compiler. And when the code is intended to be use on distributed systems, they cry... some month later. Maintain backward compatibility with enums that contains non static list of values is a real concern, and pain. This is because when you add a value to an existing enum, its type change (despite the name does not).
"Ho, wait, it may look like the same type, right? After all, they’re enums with the same name – and aren’t enums just integers under the hood?" And for these reasons, your compiler will likely not flag the use of one definition of the type itself where it was expecting the other. But in fact, they are (in most important ways) different types. Most importantly, they have different data domains – values that are acceptable given the type. By adding a value, we’ve effectively changed the type of the enum and therefore break backward compatibility.
In conclusion : Use it when you want, but, please, check that the data domain used is a finite, already known, fixed set.
The enum based singleton
a modern look at an old problem
This approach implements the singleton by taking advantage of Java's guarantee that any enum value is instantiated only once in a Java program and enum provides implicit support for thread safety. Since Java enum values are globally accessible, so they can be used as a singleton.
public enum Singleton {
SINGLETON;
public void method() { }
}
How does this work? Well, line two of the code may be considered to something like this:
public final static Singleton SINGLETON = new Singleton();
And we get good old early initialized singleton.
Remember that since this is an enum you can always access to the instance via Singleton. SINGLETON as well:
Singleton s = Singleton.SINGLETON;
Advantages
To prevent creating other instances of singleton during deserialization use enum based singleton because serialization of enum is taken care by JVM. Enum serialization and deserialization work differently than for normal java objects. The only thing that gets serialized is the name of the enum value. During the deserialization process, the enum valueOf method is used with the deserialized name to get the desired instance.
Enum based singleton allows to protect itself from reflection attacks. The enum type actually extends the java Enum class. The reason that reflection cannot be used to instantiate objects of enum type is that the java specification disallows and that rule is coded in the implementation of the newInstance method of the Constructor class, which is usually used for creating objects via reflection:
if ((clazz.getModifiers() & Modifier.ENUM) != 0)
throw new IllegalArgumentException("Cannot reflectively create enum objects");
Enum is not supposed to be cloned because there must be exactly one instance of each value.
The most laconic code among all singleton realizations.
Disadvantages
The enum based singleton does not allow lazy initialization.
If you changed your design and wanted to convert your singleton to multiton, enum would not allow this. The multiton pattern is used for the controlled creation of multiple instances, which it manages through the use of a map. Rather than having a single instance per application (e.g. the java.lang.Runtime) the multiton pattern instead ensures a single instance per key.
Enum appears only in Java 5 so you can not use it in the prior version.
There are several realizations of singleton pattern each one with advantages and disadvantages.
Eager loading singleton
Double-checked locking singleton
Initialization-on-demand holder idiom
The enum based singleton
A detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton
I would use enums as a useful mapping instrument, avoiding multiple if-else
provided that some methods are implemented.
public enum Mapping {
ONE("1"),
TWO("2");
private String label;
private Mapping(String label){
this.label = label;
}
public static Mapping by(String label) {
for(Mapping m: values() {
if(m.label.equals(label)) return m;
}
return null;
}
}
So the method by(String label) allows you to get the Enumerated value by non-enumerated. Further, one can invent mapping between 2 enums. Could also try '1 to many' or 'many to many' in addition to 'one to one' default relation
In the end, enum is a Java class. So you can have main method inside it, which might be useful when needing to do some mapping operations on args right away.
Instead of making a bunch of const int declarations
You can group them all in 1 enum
So its all organized by the common group they belong to
Enums are like classes. Like class, it also has methods and attributes.
Differences with class are:
1. enum constants are public, static , final.
2. an enum can't be used to create an object and it can't extend other classes. But it can implement interfaces.

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.

Custom fields on java enum not getting serialized

I have a Java Enum as shown below:
public enum ExecutionMode {
TYPE_A,
TYPE_B,
TYPE_C;
private ExecutionMode(){} //no args constr- no really required
private boolean incremental; //has get/set
private String someStr; //has get/set
}
I see that after deserialization, the custom fields on the enum are lost.
On reading more about it, I got the impression that enum gets deserialized into a string and hence its custom fields are ignored.
If its true, am I abusing Enum here & should just use POJO istead?
Or is there a way to serialize the custom fields (that are not part of the constructor)?
Thanks!
If the values are constant, this is better and you don't need to serialize anything
public enum ExecutionMode {
TYPE_A(x,t),
TYPE_B(y,z),
TYPE_C(b,s)
private boolean incremental; //has get/set
private String someStr; //has get/set
ExecutionMode(boolean incremental,String someStr){
///... set things appropriately
}
}
If you're setting these values at runtime, my inclination would be that this shouldn't be an enum in the first place - there should be a separate POJO that perhaps contains the values as well as a reference to an enum value.
From the Java language specification:
The final clone method in Enum ensures that enum constants can never
be cloned, and the special treatment by the serialization mechanism
ensures that duplicate instances are never created as a result of
deserialization. Reflective instantiation of enum types is prohibited.
Together, these four things ensure that no instances of an enum type
exist beyond those defined by the enum constants.
What you are asking for would create more than one instance of, say, TYPE_A. This would break enums. Enums should be immutable.

Why is an Enum considered more type-safe than constants?

In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved type-safety):
public class OfficePrinter {
public enum PrinterState { Ready, OutOfToner, Offline };
public static final PrinterState STATE = PrinterState.Ready;
}
static final char MY_A_CONST = 'a';
Imagine these two method signatures:
void rawF(char someFlag);
void enumF(MyFlags someFlag);
The latter is more restrictive as only the valid values of MyFlags are allowed. In the former case, any character could be passed - even if only the values defined in "constants" where used.
Happy coding.
You could pass MY_A_CONST to any method that takes a char. You could also pass any other char to a method that takes a char.
You could pass Ready, OutOfToner, Offline, and null to a method that takes a PrinterState.
You get safety by being able to limit the total set of values that can be passed to a method (or assigned to a variable).
Using enum over constants helps with type safety because if a function takes an enum and you pass it anything but an enum, the compiler will complain. With constants, you're accepting a pretty large range of data, most of which are invalid.

Categories

Resources