Enumerations with Java Attributes

Each color has its own static attribute - a number. I want to be able to change this value using a method. Can I do this with enumerations? Like this, or perhaps in a different way:

 public enum Color {

        RED, ORANGE, YELLOW;
}

Color.RED.setValue(x);
Color.RED.getValue();

Or did I need to do something like this, where color is a class?

public Red extends Color {
   private static int x;

   public int getRedValue(){
        return x;
   }

   public void setRedValue(int x){
        this.x = x;
   }
}
+4
source share
2 answers

Yes, you can do the following:

    enum Colour{

        RED(1), BLUE(2);

        public int value;

        Colour(int valueArg){ 
            value = valueArg; 
        }

        /*public setValue(int a){
            value = a;
        }

        public getValue(){
            return value;
        }*/

    }

    public class Test{
        static Colour colour = Colour.BLUE;
        public static void main(String[] args){
            colour.value = 3;
            //colour.setValue(3);
       }
  }

, . Colour . value (. ). , , . , .

+5

- :

public enum Color {

    RED(2), ORANGE(4), YELLOW(6);

    private int value;

    private Color (int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

}
+2

All Articles