Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How can one put to use constructor overloading in enums?

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.

like image 803
akhilless Avatar asked Jul 29 '11 08:07

akhilless


4 Answers

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...)

like image 167
Jon Skeet Avatar answered Oct 28 '22 19:10

Jon Skeet


Even more complete example:

public enum EnumTest {
  NO_ARGS, 
  FIRST_ARG("initialized string"), 
  SECOND_ARG(5), 
  BOTH_ARGS("first", Integer.MAX_VALUE);

  private final String one;
  private final int two;

  private EnumTest()
  {
    this.one = "";
    this.two = 2;
  }

  private EnumTest(String one)
  {
    this.one = one;
    this.two = 0;
  }

  private EnumTest(int two)
  {
    this.one = "";
    this.two = two;
  }

  private EnumTest(String one, int two)
  {
    this.one = one;
    this.two = two;
  }
}
like image 32
Boris Pavlović Avatar answered Oct 28 '22 20:10

Boris Pavlović


Yes, you can use constructor overloading:

public enum SomeEnum {
  VALUE1("foo"),
  VALUE2("bar", "baz");

  public final String v1;
  public final String v2;

  SomeEnum(final String v) {
    this(v, v);
  }

  SomeEnum(final String v1, final String v2) {
    this.v1 = v1;
    this.v2 = v2;
  }
}
like image 28
Joachim Sauer Avatar answered Oct 28 '22 19:10

Joachim Sauer


You use the constructor when you define your enum "constants"

enum Eg {
   ZERO, ONE(1), TWO(2,2);

   Eg() { this(0); }
   Eg(int i) { this(i, 0); }
   Eg(int i, int j) { }
}
like image 37
Peter Lawrey Avatar answered Oct 28 '22 21:10

Peter Lawrey