1

I have an enum: public enum X implements Y

I also have a class Ybuilder which can create instances of Y, let's say with Ybuilder.create(int value)

How can I set the enum values in my enum to be instances of Y created with Ybuilder? ideally it would be something simple like

public enum X implements Y {
  A (Ybuilder.create(0)),
  B (Ybuilder.create(1)),
};
3
  • X should have a constructor that takes Y as parameter type Commented Feb 29, 2016 at 18:40
  • What should that constructor do or set? Commented Feb 29, 2016 at 18:40
  • depends on what you want , you can have instance members of type T that you can set Commented Feb 29, 2016 at 18:41

1 Answer 1

6

I don't think you can do it that way - one alternative would be to delegate to the Y instance created by the builder. For example:

interface Y { //Assume Y has two methods
   void m1();
   void m2();
}

public enum X implements Y {
  A (0),
  B (1);
  private final Y y;
  X(int value) { this.y = YBuilder.create(value); }

  //Then delegate to y to implement the Y interface

  public void m1() { y.m1(); return; }
  public void m2() { y.m2(); return; }
};

Note that I created the enums with the int argument but you can pass a Y directly if you prefer:

public enum X implements Y {
  A (Ybuilder.create(0)),
  B (Ybuilder.create(1));
  private final Y y;
  X(Y y) { this.y = y; }
};
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to not have to implement all of Y's methods? Y actually has a lot of methods and it's annoying for this enum to have a bunch of methods that just return y.method();
@AndrewLatham it looks a lot like enums aren't necessarily right for this use case; that you actually just want a bunch of constants.
Of course, there is a way not to have to implement all of Y's methods. Just don’t let X implement Y. Just add one method to X to get the Y instance and you’re done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.