2

I have multiple enums each share the same constructor.

private String name;
private String value;
private EnumName(String name, String value){
  this.name = name;
  this.value = value;
}

Is there a way to extend one Enum or something along those lines so I don't have to have the code in every Enum?

Jackie
  • 21,969
  • 32
  • 147
  • 289
  • No `enum` constructors are implicitly `private` (even if you could extend them). – Sotirios Delimanolis Oct 22 '13 at 13:51
  • No, you cannot extends `Enum`. – Suresh Atta Oct 22 '13 at 13:51
  • http://i1.kym-cdn.com/entries/icons/original/000/007/423/untitle.JPG – Maroun Oct 22 '13 at 13:52
  • I think you missed my point, I didn't say it had to extend that was just the first thing that came to mind. But because of the negative reaction I think we should go ahead and delete – Jackie Oct 22 '13 at 13:56
  • @Jackie There is no such possibility. If all your enums have `name` and `value` members that you need to set, each will need its own constructor. – Sotirios Delimanolis Oct 22 '13 at 14:02
  • 1
    You can use delegation. Different `enum` classes can use the same helper class maintaining the state. But as long as the state consists of the two `String` fields “name” and “value” only it’s not worth the effort. – Holger Oct 22 '13 at 14:12

1 Answers1

2

It isn't possible - all enums extend Enum, so because Java doesn't allow multiple inheritance, an enum can't extend any other class.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Eel Lee
  • 3,513
  • 2
  • 31
  • 49
  • 1
    That's not multiple inheritance: `MyEnum extends Enum`, `MyOtherEnum extends MyEnum`. – Sotirios Delimanolis Oct 22 '13 at 13:53
  • 1
    @SotiriosDelimanolis: true, but it's still not possible since all enum classes extend *directly* from `java.lang.Enum` (except value-specific bodies, but those still don't help). – Joachim Sauer Oct 22 '13 at 13:57
  • @JoachimSauer What does enums extending `java.lang.Enum` have to do with enums not being extendable? – Sotirios Delimanolis Oct 22 '13 at 13:59
  • @SotiriosDelimanolis: it means that you can't choose another base class (that's why I emphasized "directly"). – Joachim Sauer Oct 22 '13 at 14:07
  • @Joachim This situation is the same as all classes extending from `Object`. If `A extends Object` and `B extends A`, it is not multiple inheritance. Why would `Enum` be selected as base when `MyEnum` already extends `Enum` and can be selected as base? – Sotirios Delimanolis Oct 22 '13 at 14:09
  • 2
    No, it's not the same. Java does not force all classes to *directly* extend from `Object`! *`MyEnum` can not be selected as base!* That's exactly the problem. Java does not allow that. – Joachim Sauer Oct 22 '13 at 14:11
  • @JoachimSauer Ok, I see it in JLS now, thanks. `The direct superclass of an enum type named E is Enum`. – Sotirios Delimanolis Oct 22 '13 at 14:16