Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums with attributes Java

Tags:

java

enums

Each color has its own static attribute - a number. I want to be able to change this value with a method. Can I do this using enums somehow? Like this or perhaps differently:

 public enum Color {

        RED, ORANGE, YELLOW;
}

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

Or would I have 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;
   }
}
like image 799
Gary In Avatar asked Mar 28 '15 16:03

Gary In


People also ask

Can enums have attributes Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can enums have fields?

The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.

Can you assign values to enums in Java?

By default enums have their own string values, we can also assign some custom values to enums.


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);
       }
  }

You can do this with any variable type you'd like. Here, each instantiation of the Colour enum has an associated integer value. Optionally, make the value field private and create accessor and mutator methods (see the code comments). How this works is that you provide a value for the field via a constructor that you call when you make a new instantiation of the enum. You can add more fields and arguments to the constructor as you wish.

like image 185
SamTebbs33 Avatar answered Nov 14 '22 14:11

SamTebbs33


You can do something like -

public enum Color {

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

    private int value;

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

    public int getValue() {
        return value;
    }

}
like image 25
Aniket Thakur Avatar answered Nov 14 '22 14:11

Aniket Thakur