Related
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.
How exactly does the enum in the TimeUnit API work? Particularly what does the below syntax mean?
public enum Name {
CONSTANT { }
}
I have been following the enum tutorial here, but it doesn't really go into the details of the above syntax. What is the thing inside the constant? Is it an anonymous class with their own methods? Then what are all those methods outside of the constants? I'm so confused.
In the {} the "abstract" methods are implemented.
See it as the body of a class that extends - to follow your example - "Name".
So if you have a method in Name - let's say
public String someMethod(){ throw new AbstractMethodError(); /*Or default implementation.*/ }
then you'd have to implement that in
CONSTANT{
public String someMethod() { return "green eggs and ham"; }
}
And that's what is done in TimeUnit - it defines abstract methods for converting different units and the elements implement the conversion methods for their magnitude.
Enums are classes too, their constants can be viewed as instances of the class. If you look at a normal class, if you do something like:
Clz obj = new Clz() {}
you are creating an anonymous subclass. This is true for enum values too. The methods outside of the enum values are the methods available for all the enum values(think like the public interface with default implementations, if any). If you want to override a method for a particular enum value, that's the way to do it.
I'm fairly new to java, and am used to enums essentially beeing nothing more than a named list of integers.
Now I'm writing an implementation where a parent class has a couple of methods that take an enum value as argument. The enum will be defined in child classes, and will differ slightly. Since enums basically seem to behave like classes, this doesn't work the way I expected it to. Each enum defined will be considered a different type of object and the parent class will have to pick one of the defined enums to take as argument.
Is there a good way to make the parent class accept any enum defined in it's child-classes? Or will I have to write a custom class for this?
Edit: Here is my example, fixed as per Jon Skeets answer, for anyone who is looking into how to do this later on:
class Parent {
protected interface ParentEvent {}
private HashMap<ParentEvent, String> actions = new HashMap<ParentEvent, String>();
protected void doStuff(ParentEvent e){
if(actions.containsKey(e)){
System.out.println(actions.get(e));
}
}
}
class Child extends Parent {
enum Event implements ParentEvent {EDITED, ADDED, REMOVED}
public void trigger(){
doStuff(Event.REMOVED);
}
}
You could make your enums implement an interface, then give your parent class method a parameter of that interface type.
As you say, enums are rather different in Java. They're not named numbers - they're a fixed set of values, but those values are object-oriented (i.e. they can use polymorphism etc). Java enums pretty much rock, except for a few tricksy issues around initialization ordering.
if i understand you correctly, you want to have a common base class for your enum and want to define several unrelated sets of enums for the sub classes. This is not possible with java's typesafe enums, because they don't allow you to define a base class.
Of course it is not an option just to have one enum defined and always extend its values because this clearly violates the open close principle.
For such a use case I have fairly good experience with Josh Bloch's Typesafe Enum Pattern he describes in Effective Java
Just introduce your super class here and make distinct sub classes for each of enum values your client classes need.
I'm not sure, but maybe this is what you want:
public abstract class EnumTest<E extends Enum<E>> {
public abstract void frobnicate(E value);
}
public class Derived extends EnumTest<Derived.DerivedEnum> {
public void frobnicate(DerivedEnum value) {
System.out.println(value);
}
public static enum DerivedEnum {
FOO, BAR,
}
}
You could define the enums in their own file if they're applicable to different classes. They don't need to be nested within a class.
You can't extend one set of enums from another though.
It took me a while to get out of the mindset of an enum 'just being an integer'.
EDIT: As of Java 8, static methods are now allowed in interfaces.
Here's the example:
public interface IXMLizable<T>
{
static T newInstanceFromXML(Element e);
Element toXMLElement();
}
Of course this won't work. But why not?
One of the possible issues would be, what happens when you call:
IXMLizable.newInstanceFromXML(e);
In this case, I think it should just call an empty method (i.e. {}). All subclasses would be forced to implement the static method, so they'd all be fine when calling the static method. So why isn't this possible?
EDIT: I guess I'm looking for answer that's deeper than "because that's the way Java is".
Is there a particular technological reason why static methods can't be overwritten? That is, why did the designers of Java decide to make instance methods overrideable but not static methods?
EDIT: The problem with my design is I'm trying to use interfaces to enforce a coding convention.
That is, the goal of the interface is twofold:
I want the IXMLizable interface to allow me to convert classes that implement it to XML elements (using polymorphism, works fine).
If someone wants to make a new instance of a class that implements the IXMLizable interface, they will always know that there will be a newInstanceFromXML(Element e) static constructor.
Is there any other way to ensure this, other than just putting a comment in the interface?
Java 8 permits static interface methods
With Java 8, interfaces can have static methods. They can also have concrete instance methods, but not instance fields.
There are really two questions here:
Why, in the bad old days, couldn't interfaces contain static methods?
Why can't static methods be overridden?
Static methods in interfaces
There was no strong technical reason why interfaces couldn't have had static methods in previous versions. This is summed up nicely by the poster of a duplicate question. Static interface methods were initially considered as a small language change, and then there was an official proposal to add them in Java 7, but it was later dropped due to unforeseen complications.
Finally, Java 8 introduced static interface methods, as well as override-able instance methods with a default implementation. They still can't have instance fields though. These features are part of the lambda expression support, and you can read more about them in Part H of JSR 335.
Overriding static methods
The answer to the second question is a little more complicated.
Static methods are resolvable at compile time. Dynamic dispatch makes sense for instance methods, where the compiler can't determine the concrete type of the object, and, thus, can't resolve the method to invoke. But invoking a static method requires a class, and since that class is known statically—at compile time—dynamic dispatch is unnecessary.
A little background on how instance methods work is necessary to understand what's going on here. I'm sure the actual implementation is quite different, but let me explain my notion of method dispatch, which models observed behavior accurately.
Pretend that each class has a hash table that maps method signatures (name and parameter types) to an actual chunk of code to implement the method. When the virtual machine attempts to invoke a method on an instance, it queries the object for its class and looks up the requested signature in the class's table. If a method body is found, it is invoked. Otherwise, the parent class of the class is obtained, and the lookup is repeated there. This proceeds until the method is found, or there are no more parent classes—which results in a NoSuchMethodError.
If a superclass and a subclass both have an entry in their tables for the same method signature, the sub class's version is encountered first, and the superclass's version is never used—this is an "override".
Now, suppose we skip the object instance and just start with a subclass. The resolution could proceed as above, giving you a sort of "overridable" static method. The resolution can all happen at compile-time, however, since the compiler is starting from a known class, rather than waiting until runtime to query an object of an unspecified type for its class. There is no point in "overriding" a static method since one can always specify the class that contains the desired version.
Constructor "interfaces"
Here's a little more material to address the recent edit to the question.
It sounds like you want to effectively mandate a constructor-like method for each implementation of IXMLizable. Forget about trying to enforce this with an interface for a minute, and pretend that you have some classes that meet this requirement. How would you use it?
class Foo implements IXMLizable<Foo> {
public static Foo newInstanceFromXML(Element e) { ... }
}
Foo obj = Foo.newInstanceFromXML(e);
Since you have to explicitly name the concrete type Foo when "constructing" the new object, the compiler can verify that it does indeed have the necessary factory method. And if it doesn't, so what? If I can implement an IXMLizable that lacks the "constructor", and I create an instance and pass it to your code, it is an IXMLizable with all the necessary interface.
Construction is part of the implementation, not the interface. Any code that works successfully with the interface doesn't care about the constructor. Any code that cares about the constructor needs to know the concrete type anyway, and the interface can be ignored.
This was already asked and answered, here
To duplicate my answer:
There is never a point to declaring a static method in an interface. They cannot be executed by the normal call MyInterface.staticMethod(). If you call them by specifying the implementing class MyImplementor.staticMethod() then you must know the actual class, so it is irrelevant whether the interface contains it or not.
More importantly, static methods are never overridden, and if you try to do:
MyInterface var = new MyImplementingClass();
var.staticMethod();
the rules for static say that the method defined in the declared type of var must be executed. Since this is an interface, this is impossible.
The reason you can't execute "result=MyInterface.staticMethod()" is that it would have to execute the version of the method defined in MyInterface. But there can't be a version defined in MyInterface, because it's an interface. It doesn't have code by definition.
While you can say that this amounts to "because Java does it that way", in reality the decision is a logical consequence of other design decisions, also made for very good reason.
With the advent of Java 8 it is possible now to write default and static methods in interface.
docs.oracle/staticMethod
For example:
public interface Arithmetic {
public int add(int a, int b);
public static int multiply(int a, int b) {
return a * b;
}
}
public class ArithmaticImplementation implements Arithmetic {
#Override
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = Arithmetic.multiply(2, 3);
System.out.println(result);
}
}
Result : 6
TIP : Calling an static interface method doesn't require to be implemented by any class. Surely, this happens because the same rules for static methods in superclasses applies for static methods on interfaces.
Normally this is done using a Factory pattern
public interface IXMLizableFactory<T extends IXMLizable> {
public T newInstanceFromXML(Element e);
}
public interface IXMLizable {
public Element toXMLElement();
}
Because static methods cannot be overridden in subclasses, and hence they cannot be abstract. And all methods in an interface are, de facto, abstract.
Why can't I define a static method in a Java interface?
Actually you can in Java 8.
As per Java doc:
A static method is a method that is associated with the class in which
it is defined rather than with any object. Every instance of the class
shares its static methods
In Java 8 an interface can have default methods and static methods. This makes it easier for us to organize helper methods in our libraries. We can keep static methods specific to an interface in the same interface rather than in a separate class.
Example of default method:
list.sort(ordering);
instead of
Collections.sort(list, ordering);
Example of static method (from doc itself):
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
Interfaces are concerned with polymorphism which is inherently tied to object instances, not classes. Therefore static doesn't make sense in the context of an interface.
First, all language decisions are decisions made by the language creators. There is nothing in the world of software engineering or language defining or compiler / interpreter writing which says that a static method cannot be part of an interface. I've created a couple of languages and written compilers for them -- it's all just sitting down and defining meaningful semantics. I'd argue that the semantics of a static method in an interface are remarkably clear -- even if the compiler has to defer resolution of the method to run-time.
Secondly, that we use static methods at all means there is a valid reason for having an interface pattern which includes static methods -- I can't speak for any of you, but I use static methods on a regular basis.
The most likely correct answer is that there was no perceived need, at the time the language was defined, for static methods in interfaces. Java has grown a lot over the years and this is an item that has apparently gained some interest. That it was looked at for Java 7 indicates that its risen to a level of interest that might result in a language change. I, for one, will be happy when I no longer have to instantiate an object just so I can call my non-static getter method to access a static variable in a subclass instance ...
"Is there a particular reason that static methods cannot be overridden".
Let me re-word that question for your by filling in the definitions.
"Is there a particular reason that methods resolved at compile time cannot be resolved at runtime."
Or, to put in more completely, If I want to call a method without an instance, but knowing the class, how can I have it resolved based upon the instance that I don't have.
Static methods aren't virtual like instance methods so I suppose the Java designers decided they didn't want them in interfaces.
But you can put classes containing static methods inside interfaces. You could try that!
public interface Test {
static class Inner {
public static Object get() {
return 0;
}
}
}
Commenting EDIT: As of Java 8, static methods are now allowed in interfaces.
It is right, static methods since Java 8 are allowed in interfaces, but your example still won't work. You cannot just define a static method: you have to implement it or you will obtain a compilation error.
Several answers have discussed the problems with the concept of overridable static methods. However sometimes you come across a pattern where it seems like that's just what you want to use.
For example, I work with an object-relational layer that has value objects, but also has commands for manipulating the value objects. For various reasons, each value object class has to define some static methods that let the framework find the command instance. For example, to create a Person you'd do:
cmd = createCmd(Person.getCreateCmdId());
Person p = cmd.execute();
and to load a Person by ID you'd do
cmd = createCmd(Person.getGetCmdId());
cmd.set(ID, id);
Person p = cmd.execute();
This is fairly convenient, however it has its problems; notably the existence of the static methods can not be enforced in the interface. An overridable static method in the interface would be exactly what we'd need, if only it could work somehow.
EJBs solve this problem by having a Home interface; each object knows how to find its Home and the Home contains the "static" methods. This way the "static" methods can be overridden as needed, and you don't clutter up the normal (it's called "Remote") interface with methods that don't apply to an instance of your bean. Just make the normal interface specify a "getHome()" method. Return an instance of the Home object (which could be a singleton, I suppose) and the caller can perform operations that affect all Person objects.
Why can't I define a static method in a Java interface?
All methods in an interface are explicitly abstract and hence you cannot define them as static because static methods cannot be abstract.
Well, without generics, static interfaces are useless because all static method calls are resolved at compile time. So, there's no real use for them.
With generics, they have use -- with or without a default implementation. Obviously there would need to be overriding and so on. However, my guess is that such usage wasn't very OO (as the other answers point out obtusely) and hence wasn't considered worth the effort they'd require to implement usefully.
An interface can never be dereferenced statically, e.g. ISomething.member. An interface is always dereferenced via a variable that refers to an instance of a subclass of the interface. Thus, an interface reference can never know which subclass it refers to without an instance of its subclass.
Thus the closest approximation to a static method in an interface would be a non-static method that ignores "this", i.e. does not access any non-static members of the instance. At the low-level abstraction, every non-static method (after lookup in any vtable) is really just a function with class scope that takes "this" as an implicit formal parameter. See Scala's singleton object and interoperability with Java as evidence of that concept.
And thus every static method is a function with class scope that does not take a "this" parameter. Thus normally a static method can be called statically, but as previously stated, an interface has no implementation (is abstract).
Thus to get closest approximation to a static method in an interface, is to use a non-static method, then don't access any of the non-static instance members. There would be no possible performance benefit any other way, because there is no way to statically link (at compile-time) a ISomething.member(). The only benefit I see of a static method in an interface is that it would not input (i.e. ignore) an implicit "this" and thus disallow access to any of the non-static instance members. This would declare implicitly that the function that doesn't access "this", is immutate and not even readonly with respect to its containing class. But a declaration of "static" in an interface ISomething would also confuse people who tried to access it with ISomething.member() which would cause a compiler error. I suppose if the compiler error was sufficiently explanatory, it would be better than trying to educate people about using a non-static method to accomplish what they want (apparently mostly factory methods), as we are doing here (and has been repeated for 3 Q&A times on this site), so it is obviously an issue that is not intuitive for many people. I had to think about it for a while to get the correct understanding.
The way to get a mutable static field in an interface is use non-static getter and setter methods in an interface, to access that static field that in the subclass. Sidenote, apparently immutable statics can be declared in a Java interface with static final.
Interfaces just provide a list of things a class will provide, not an actual implementation of those things, which is what your static item is.
If you want statics, use an abstract class and inherit it, otherwise, remove the static.
Hope that helps!
You can't define static methods in an interface because static methods belongs to a class not to an instance of class, and interfaces are not Classes. Read more here.
However, If you want you can do this:
public class A {
public static void methodX() {
}
}
public class B extends A {
public static void methodX() {
}
}
In this case what you have is two classes with 2 distinct static methods called methodX().
Suppose you could do it; consider this example:
interface Iface {
public static void thisIsTheMethod();
}
class A implements Iface {
public static void thisIsTheMethod(){
system.out.print("I'm class A");
}
}
class B extends Class A {
public static void thisIsTheMethod(){
System.out.print("I'm class B");
}
}
SomeClass {
void doStuff(Iface face) {
IFace.thisIsTheMethod();
// now what would/could/should happen here.
}
}
Something that could be implemented is static interface (instead of static method in an interface). All classes implementing a given static interface should implement the corresponding static methods. You could get static interface SI from any Class clazz using
SI si = clazz.getStatic(SI.class); // null if clazz doesn't implement SI
// alternatively if the class is known at compile time
SI si = Someclass.static.SI; // either compiler errror or not null
then you can call si.method(params).
This would be useful (for factory design pattern for example) because you can get (or check the implementation of) SI static methods implementation from a compile time unknown class !
A dynamic dispatch is necessary and you can override the static methods (if not final) of a class by extending it (when called through the static interface).
Obviously, these methods can only access static variables of their class.
While I realize that Java 8 resolves this issue, I thought I'd chime in with a scenario I am currently working on (locked into using Java 7) where being able to specify static methods in an interface would be helpful.
I have several enum definitions where I've defined "id" and "displayName" fields along with helper methods evaluating the values for various reasons. Implementing an interface allows me to ensure that the getter methods are in place but not the static helper methods. Being an enum, there really isn't a clean way to offload the helper methods into an inherited abstract class or something of the like so the methods have to be defined in the enum itself. Also because it is an enum, you wouldn't ever be able to actually pass it as an instanced object and treat it as the interface type, but being able to require the existence of the static helper methods through an interface is what I like about it being supported in Java 8.
Here's code illustrating my point.
Interface definition:
public interface IGenericEnum <T extends Enum<T>> {
String getId();
String getDisplayName();
//If I was using Java 8 static helper methods would go here
}
Example of one enum definition:
public enum ExecutionModeType implements IGenericEnum<ExecutionModeType> {
STANDARD ("Standard", "Standard Mode"),
DEBUG ("Debug", "Debug Mode");
String id;
String displayName;
//Getter methods
public String getId() {
return id;
}
public String getDisplayName() {
return displayName;
}
//Constructor
private ExecutionModeType(String id, String displayName) {
this.id = id;
this.displayName = displayName;
}
//Helper methods - not enforced by Interface
public static boolean isValidId(String id) {
return GenericEnumUtility.isValidId(ExecutionModeType.class, id);
}
public static String printIdOptions(String delimiter){
return GenericEnumUtility.printIdOptions(ExecutionModeType.class, delimiter);
}
public static String[] getIdArray(){
return GenericEnumUtility.getIdArray(ExecutionModeType.class);
}
public static ExecutionModeType getById(String id) throws NoSuchObjectException {
return GenericEnumUtility.getById(ExecutionModeType.class, id);
}
}
Generic enum utility definition:
public class GenericEnumUtility {
public static <T extends Enum<T> & IGenericEnum<T>> boolean isValidId(Class<T> enumType, String id) {
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
if(enumOption.getId().equals(id)) {
return true;
}
}
return false;
}
public static <T extends Enum<T> & IGenericEnum<T>> String printIdOptions(Class<T> enumType, String delimiter){
String ret = "";
delimiter = delimiter == null ? " " : delimiter;
int i = 0;
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
if(i == 0) {
ret = enumOption.getId();
} else {
ret += delimiter + enumOption.getId();
}
i++;
}
return ret;
}
public static <T extends Enum<T> & IGenericEnum<T>> String[] getIdArray(Class<T> enumType){
List<String> idValues = new ArrayList<String>();
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
idValues.add(enumOption.getId());
}
return idValues.toArray(new String[idValues.size()]);
}
#SuppressWarnings("unchecked")
public static <T extends Enum<T> & IGenericEnum<T>> T getById(Class<T> enumType, String id) throws NoSuchObjectException {
id = id == null ? "" : id;
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
if(id.equals(enumOption.getId())) {
return (T)enumOption;
}
}
throw new NoSuchObjectException(String.format("ERROR: \"%s\" is not a valid ID. Valid IDs are: %s.", id, printIdOptions(enumType, " , ")));
}
}
Let's suppose static methods were allowed in interfaces:
* They would force all implementing classes to declare that method.
* Interfaces would usually be used through objects, so the only effective methods on those would be the non-static ones.
* Any class which knows a particular interface could invoke its static methods. Hence a implementing class' static method would be called underneath, but the invoker class does not know which. How to know it? It has no instantiation to guess that!
Interfaces were thought to be used when working with objects. This way, an object is instantiated from a particular class, so this last matter is solved. The invoking class need not know which particular class is because the instantiation may be done by a third class. So the invoking class knows only the interface.
If we want this to be extended to static methods, we should have the possibility to especify an implementing class before, then pass a reference to the invoking class. This could use the class through the static methods in the interface. But what is the differente between this reference and an object? We just need an object representing what it was the class. Now, the object represents the old class, and could implement a new interface including the old static methods - those are now non-static.
Metaclasses serve for this purpose. You may try the class Class of Java. But the problem is that Java is not flexible enough for this. You can not declare a method in the class object of an interface.
This is a meta issue - when you need to do ass
..blah blah
anyway you have an easy workaround - making the method non-static with the same logic. But then you would have to first create an object to call the method.
To solve this :
error: missing method body, or declare abstract
static void main(String[] args);
interface I
{
int x=20;
void getValue();
static void main(String[] args){};//Put curly braces
}
class InterDemo implements I
{
public void getValue()
{
System.out.println(x);
}
public static void main(String[] args)
{
InterDemo i=new InterDemo();
i.getValue();
}
}
output :
20
Now we can use static method in interface
I think java does not have static interface methods because you do not need them. You may think you do, but...
How would you use them? If you want to call them like
MyImplClass.myMethod()
then you do not need to declare it in the interface. If you want to call them like
myInstance.myMethod()
then it should not be static.
If you are actually going to use first way, but just want to enforce each implementation to have such static method, then it is really a coding convention, not a contract between instance that implements an interface and calling code.
Interfaces allow you to define contract between instance of class that implement the interface and calling code. And java helps you to be sure that this contract is not violated, so you can rely on it and don't worry what class implements this contract, just "someone who signed a contract" is enough. In case of static interfaces your code
MyImplClass.myMethod()
does not rely on the fact that each interface implementation has this method, so you do not need java to help you to be sure with it.
What is the need of static method in interface, static methods are used basically when you don't have to create an instance of object whole idea of interface is to bring in OOP concepts with introduction of static method you're diverting from concept.
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