jaySon
jaySon

Reputation: 815

How to implement an enum which is needed in two different classes?

Class Action:

public class Action {
    public static enum Type {
        POSITION, MOUSE, KEY, TEXT
    }

    public final Type type;

    public Action() {
        this.type = Type.KEY;
    }

    //properties, getters, setters ...
}

Class Model:

public class Model {
    public static enum Type {
        POSITION, MOUSE, KEY, TEXT
    }

    public final Type type;

    public void doSomething() {
        Action action = new Action();
        switch (action.type) {
            case this.Type.POSITION: //cannot convert from Model.Type to Action.Type
                //do stuff here
                break;
            case ...
                //more stuff here
                break;
            default:
                //default stuff here
                break;
        }
    }
}

This was my (simplified) initial approach which obviously doesn't work. The Model needs to do some operation, dependent on what Type the Action has and I would like to determine that without having to cross borders between the two classes, meaning I hope there is a better solution than the following:

Action.Type type = action.type;

Upvotes: 1

Views: 244

Answers (1)

Prim
Prim

Reputation: 2968

You must extract the enum into a separated source file, like a class but with a type 'enum' :

public enum Type {
    POSITION, 
    MOUSE, 
    KEY, 
    TEXT
}

and access it into your classes by importing it.

You can also keep the enum into one of your class with static keyword, and access to it in the another class by adding an import statement

Upvotes: 3

Related Questions