Reputation: 19731
I want to assign an enum an enum value like
enum 1
public enum e1{
value1,
value2;
}
enum 2
public enum e2{
val1 ( some value from e1 ),
val2 ( some value from e1 );
}
I should also be able to change the value of val1
later depending on the conditions.
How is that possible in Java?
Upvotes: 0
Views: 488
Reputation: 2863
You can have a member variable in an Enum if you provide a constructor :
public enum e2{
A2(e1.B1),
B2(e1.B1),
C2(e1.A1);
e1 e1Value;
e2(e1 e1NewValue){
e1Value = e1NewValue;
}
}
public enum e1{
A1, B1;
}
Upvotes: 2
Reputation: 9741
Mutable enum, ouch. Technically possible, but i'd advise against it. If its just one time value at the time of intialization, its perfectly fine and good.
public enum e1{
value1("1"),
value2("2");
String val;
private e1(String v) {
val = v;
}
//bad don't use
public void setValue(String v){
val = v;
}
public String getValue(){
return val;
}
}
//usage
e1.value1.setValue("3");
e1.value1.setValue("4");
Upvotes: 1
Reputation: 308001
Enums are basically classes in Java, so you can just make a property:
public enum E2 {
VAL1(E1.VALUE1),
VAL2(E2.VALUE2);
public final E1 e1Value;
E2(E1 e1Value) {
this.e1Value = e1Value;
}
}
You could also make a getter/setter for e1Value
, but I'd strongly discourage this. While nothing technically stops you from making a modifyable field in an enum, it is highly unusual and unexpected and will lead to confusing and/or subtle bugs.
Upvotes: 7
Reputation: 13047
You can do something like this:
public enum E1 {
A, B;
}
and then:
public enum E2 {
C(E1.A), D(E1.B);
private final E1 e1;
private E2(E1 e1) {
this.e1 = e1;
}
public E1 getE1() {
return e1;
}
}
Upvotes: 3