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;
}
}
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).
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
You can have methods on enums which take parameters. Java enums are not union types like in some other languages.
By default enums have their own string values, we can also assign some custom values to enums.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With