Question

I'm looking to have a base enum like this...

public enum SessionState {

    WAITING(true), VOTING(true), PREPARING(false), PLAYING(false), ENDING(false);

    boolean newPlayersJoin;

    private SessionState(boolean newPlayersJoin){
        this.newPlayersJoin = newPlayersJoin;
    }

    public boolean canNewPlayersJoin(){
        return newPlayersJoin;   
    }

}

...and then another enum with the same values (WAITING, VOTING, PREPARING, PLAYING, ENDING) but with more functions. The reason I want a base enum without the extra methods is that some of the methods depend on functions that won't be included in that jar file (multi-module project)

My other enum would look something like this

public enum SessionStateCopy {

    WAITING(true, ... extra values), VOTING(true, ... extra values), PREPARING(false, ... extra values), PLAYING(false, ... extra values), ENDING(false, ... extra values);

    boolean newPlayersJoin;

    private SessionStateCopy(boolean newPlayersJoin, ... extra values){
        this.newPlayersJoin = newPlayersJoin;
    }

    public boolean canNewPlayersJoin(){
        return newPlayersJoin;   
    }

    ... extra methods

}
Was it helpful?

Solution

enums in Java are implicitly final, so you can't inherit them from each other. I'd have the two different enums, like you have in the OP, and add a couple of methods to convert between them:

public static SessionState convert(SessionStateCopy s) {
    return SessionState.valueOf(s.name());
}

public static SessionStateCopy convert(SessionState s) {
    return SessionStateCopy .valueOf(s.name());
}

Just to make sure you don't accidently add a value to one and not the other, I'd add a JUnit test to ensure this:

// imports snipped for clarity
public class SessionStateTest() {

    public void testMatchingMembers() {
        assertEquals("wrong number of values", SessionState.values().size(), SessionStateCopy.values().size());
        for (SessionState s: SessionState.values()) {
            assertEquals ("wrong value", s, convert(convert(s));
        }
    }
}

OTHER TIPS

If I understand your question correctly, you want an enum to extend an enum.

You cannot.

However, you can have two enums implementing the same interface.

The one that's poorer in functionality would implements all methods but do nothing.

The other one would provide a "useful" implementation of the interface's methods.

For instance:

enum Foo { // "extends Bar" would not compile
    FOO();
}
interface Blah {
    void meh();
}
enum Bar implements Blah {
    SOMETHING();
    public void meh() {
        // nope     
    }
}
enum GreatBar implements Blah {
    SOMETHING();
    public void meh() {
        System.out.println("I'm doing something here!");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top