I've seen two approaches to handling enums with properties. Is one better than the other?
As a property:
public enum SEARCH_ENGINE {
GOOGLE("http://www.google.com"),
BING("http://www.bing.com");
private final String url;
private SEARCH_ENGINE(String url) {
this.url = url;
}
public String getURL() {
return url;
}
}
As a method:
public enum SEARCH_ENGINE {
GOOGLE {
public String getURL() {return "http://www.google.com";}
},
BING {
public String getURL() {return "http://www.bing.com";}
};
public abstract String getURL();
}
Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.
The first clearly looks cleaner to me - it makes use of the commonality that each element of the enum will have a fixed String URL which is known at initialization. You're effectively repeating that "logic" in each implementation in the second version. You're overriding a method to provide the same logic ("just return a string which is known at compile-time") in each case. I prefer to reserve overriding for changes in behaviour.
I suggest making the url
field private though, in the first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With