1

Possible Duplicate:
Java enum inheritance

I'm working with a library that has an enumerated type that's perfect for my uses, but the name is horrible and confusing. Can I simply inherit from this enum to create my own with a much nicer name?

public enum Settings extends JiggidyWapperfragNautchFrick.SkiddidyBoomCaFriglets {
}

Like so? IntelliJ complained when I tried to do this, but what would be the appropriate way to get the effect of what I'm proposing?

Community
  • 1
  • 1
Kieveli
  • 10,944
  • 6
  • 56
  • 81

4 Answers4

4

No, you can't extend an enum class.

The only (slight) exception is that an enum value can have a value-specific class body, which effectively creates a separate class extending the original enum class.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
3

enums are final classes so you cannot sub class them. I would advise to wrap it in another class that is nicely named.

Perhaps something like this. By having the private ctor you cannot instantiate it.

public class Nice {

    private Nice(){}

    public static badNamedEnum one(){
        return badNamedEnum.badNamedOne;
    }

    public static badNamedEnum two(){
        return badNamedEnum.badNamedTwo;
    }
}
RNJ
  • 15,272
  • 18
  • 86
  • 131
  • So basically define my enum with its defined values referencing the other enum? Not as dynamic, but it could work... – Kieveli Sep 14 '12 at 12:20
  • Yep like that or wrap in a class which wraps the enum – RNJ Sep 14 '12 at 12:23
  • 1
    `Nice` could also be another enum (perhaps even taking the 'original' enum as a parameter to its private constructor), that would be a little neater still. – Arnout Engelen Sep 14 '12 at 12:28
  • 1
    This won't help if you want a List of values - you'll still need the long class name. – Kieveli Sep 14 '12 at 12:29
  • You could modify this with `public static final BadlyNamedEnum` fields for all the values and even a `values` method that returns a `BadlyNamedEnum[]` ... your *arguments* and variables will still use `BadlyNamedEnum` as the type, but at least for *value references* you could use `BetterEnum.THE_VALUE`. – Joachim Sauer Sep 17 '12 at 07:52
0

Joachim is right, but an enum can implement an interface.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Enums are used to "hardcode" switches and other tests. Allowing subclassing would make no sense and would defeat the purpose as this would allow an incertitude on the possible values.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    What he _really_ wants is not a subclass, but another name for the same type. in Java AFAIK the only real way to get that is subclassing, which (indeed and obviously) won't work for final classes. Unfortunately Java doesn't have something like `typedef` from C or type synonyms from Haskell et al – Arnout Engelen Sep 14 '12 at 12:24