I am working with enumerations in Java. As I can see, it is possible to overload an enumeration constructor. My question is it possible at all to benefit from constructor overloading in this context given that as far as I understand it is possible neither to call it by yourself no to force the compiler to call a particular one that you would like to call?
Appreciate the time your take to clarify that stuff to me and hope it would also be useful for others who might have the same question in mind.
解决方案
You do call it - when setting the enum values. For example:
public enum Person
{
FRED("Frederick", "Fred"),
PETE("Peter", "Pete"),
MALCOLM("Malcolm"); // No nickname
private final String nickname;
private final String name;
private Person(String name, String nickname)
{
this.name = name;
this.nickname = nickname;
}
private Person(String name)
{
this(name, name); // Just use the name as the nickname too
}
// getNickname and getName
}
I've used this ability for various projects in the past. Enums are one of Java's nicest features - certainly one of the few things I miss from Java when working in C#. (They could be implemented even more neatly, I'm sure, but...)