jlengrand
jlengrand

Reputation: 12827

Create a superclass of enum

I currently use an enum defined as such :

public enum Language{
    English("english", "eng", "en", "en_GB", "en_US"),
    German("german", "de", "ge"),
    Croatian("croatian", "hr", "cro"),
    Russian("russian");

    private final List<String> values;

    Language(String ...values) {
        this.values = Arrays.asList(values);
    }

    public List<String> getValues() {
        return values;
    }
    public static Language find(String name) {
        for (Language lang : Language.values()) {
            if (lang.getValues().contains(name)) {
                return lang;
            }
        }
        return null;
    }
}

Thing is, I will have to use several enums using the same methods and constructor. The only thing changing would in my case be the values of the enum itself.

Is there a way for me to create a superclass of this enum that I could reuse ?

So that I could do something like :

public Language extends(specializedEnum){
        English("english", "eng", "en", "en_GB", "en_US"),
        German("german", "de", "ge"),
        Croatian("croatian", "hr", "cro"),
        Russian("russian");
}

Thank you by advance !

Upvotes: 2

Views: 13042

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200306

There are difficulties with this in Java, but a solution that will give you a good deal of what you need is to make all your enums implement a common interface.

You'll have trouble reusing the code for the methods that implement the interface, but you can mitigate the damage by delegating the real work to outside methods.

Also, often a lookup-by-name function will be needed that gives you the right enum member regardless of the exact enum class. This can be accomplished using a separate HashMap that aggregates all enum members.

Basically, this is the outline of how I'm doing it in a project right now.

Upvotes: 10

Reimeus
Reimeus

Reputation: 159874

Its simply not possible to extend Enums but you could implement an common interface to add extra functionality.

public interface BaseLanguage {
   public void doStuff();
}

public enum Language implements BaseLanguage {
    English("english", "eng", "en", "en_GB", "en_US"),

   // etc.

   @Override
   public void doStuff() {
     // do work based on current Language enum
   }
}

Upvotes: 5

Toilal
Toilal

Reputation: 3409

Enum can't be extended in Java.

Upvotes: 5

Related Questions