Java: how can constructor overload be used in enums?

I work with listings in Java. As I can see, you can overload the enumeration constructor. My question is, is it even possible to use constructor overloading in this context, given that, as I understand it, it is impossible not to name it yourself to make the compiler not call the one you would like to name?

Appreciate the time you want to clarify this material to me and hope that it will also be useful to others who may have the same question.

+3
source share
5 answers

You invoke this when setting the enumeration values. For instance:

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
}

. Enums - Java - , , Java #. ( , , ...)

+14

:

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;
  }
}
+3

, :

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;
  }
}
+2

, ""

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

   Eg() { this(0); }
   Eg(int i) { this(i, 0); }
   Eg(int i, int j) { }
}
+2

, ? , switch .

ZoneGroup zoneGroup = ZoneGroup.get(loader.getId());

public static enum ZoneGroup {
    ANDROID_NOTABLE(0), ANDROID_TOP(1), ANDROID_ALL(2), ANDROID_NEAR(3), ANDROID_FAV(4), UNDEFINED(5);

    private final int value;

    ZoneGroup(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static ZoneGroup get(int value){
        switch (value) {
        case 0:
            return ANDROID_NOTABLE;
        case 1:
            return ANDROID_TOP;
        case 2:
            return ANDROID_ALL;
        case 3:
            return ANDROID_NEAR;
        case 4:
            return ANDROID_FAV;
        default:
            return UNDEFINED;
        }
    }
}
0

All Articles