Creating an objects what associated to one but have not same features

user11731595 :

Hi all who read that.

I create a simple bukkit plugin and need some help with some features of the plugin.

What i need to do: All items have an "Action" what must do when player click to that Item, i have 3 Actions and that is my enum for action types

public enum GUIItemType {

    COMMAND,
    SEND,
    NOTHING;

}

But l doesn`t know how to associate values into that by code (with 1 type may be different values) I suspose that i must use abstract classes or interfaces but doesn`t good understood how, can you help please?

Sorry for my english

Joni :

An enum in Java can have fields and methods, which makes them incredibly powerful. For example, this is how each action type could have different associated values:

public enum GUIItemType {

    COMMAND(987),
    SEND(654),
    NOTHING(321);

    private final int value;

    GUIItemType(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

GUIItemType.SEND.getValue() would return 654.

Each enum item can even have different behavior: the items can override methods.

public enum GUIItemType {

    COMMAND(987) {
        @Override
        int compute(int a) {
            return a + value;
        }
    },
    SEND(654) {
        @Override
        int compute(int a) {
            return a - value;
        }
    },
    NOTHING(321) {
        @Override
        int compute(int a) {
            return a * value;
        }
    };

    final int value;

    GUIItemType(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    abstract int compute(int value);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=384963&siteId=1