0

Can I add enums inside other enums? For example:

public enum Enum1 {
    VALUE1;
}
public enum Enum2 {
    Enum1,
    VALUE2;
}

Note: I already know that you can do it like this way:

public enum Action
{
   FOO,
   BAR;
   enum MOVE
   {
     UP,
     DOWN,
     LEFT,
     RIGHT 
   }
}
Jason Glez
  • 1,254
  • 1
  • 16
  • 16
  • 1
    Possible duplicate https://stackoverflow.com/questions/1414755/ – killjoy Jun 01 '18 at 21:59
  • 3
    Your first code doesn't make sense since an enum identifier has to be, well, an identifier, like any other, and suggests an [XY Problem](http://xyproblem.info) -- what issue are you trying to solve with this? You already know that that "code" does not compile, and so you know that it's not legal. – Hovercraft Full Of Eels Jun 01 '18 at 22:00
  • @killjoy I don't want to extend the enum, I just want to have it like another property. – Jason Glez Jun 01 '18 at 22:02
  • Possible duplicate of [Can enums be subclassed to add new elements?](https://stackoverflow.com/questions/1414755/can-enums-be-subclassed-to-add-new-elements) – Jacob G. Jun 01 '18 at 22:03
  • Possible duplicate [Java Enum referencing another enum](https://stackoverflow.com/questions/5172178) – UkFLSUI Jun 01 '18 at 22:03
  • I think the closest you can get is to wrap it. – killjoy Jun 01 '18 at 22:04
  • 1
    Possible duplicate of [Java Enum referencing another enum](https://stackoverflow.com/questions/5172178/java-enum-referencing-another-enum) – UkFLSUI Jun 01 '18 at 22:05
  • @HovercraftFullOfEels It was just a generic example to know how I can do that. If you want to know my real problem: I have an enum to display output messages and I want to "extend" the funtionality adding more output messages. Like this: public enum GenericResponse { SUCCESS(1, "Successful operation"), SERVER_ERROR(2, "Error processing request"), MISSING_PARAMETERS(3, "Missing parameters"); } public enum AuthenticationResponse { //Generic messages NOT_ALLOWED(4, "User not allowed"); } – Jason Glez Jun 01 '18 at 22:08
  • If you need flexible and extensible messages, then don't use Java enums for this. Instead use a plain Java class, one where Strings can be added as needed, perhaps via database or via text setup file. – Hovercraft Full Of Eels Jun 01 '18 at 22:14

1 Answers1

1
public enum Enum1 {
    VALUE1;
}
public enum Enum2 {
    Enum1, // Enum1 is just constant
    VALUE2;
}

It's possible, but Enum1 in Enum2 is just constant (without any dependency with Enum1 enum), however you can use something like this:

public enum Enum1 {
   VALUE1;
}

public enum Enum2 {
    VALUE1 (Enum1.VALUE1),
    VALUE2 (null);

    private final Enum1 enum1;

    Enum2(com.github.vedenin.services.image.filter.Enum1 enum1) {
        this.enum1 = enum1;
    }

    public Enum1 getEnum1() {
        return enum1;
    }
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59