Help with Enums in Java

Is it possible for enum to change its meaning (from within itself)? It may be easier to understand what I mean by code:

enum Rate { VeryBad(1), Bad(2), Average(3), Good(4), Excellent(5); private int rate; private Rate(int rate) { this.rate = rate; } public void increateRating() { //is it possible to make the enum variable increase? //this is, if right now this enum has as value Average, after calling this //method to have it change to Good? } } 

This is the desire I want to achieve:

 Rate rate = Rate.Average; System.out.println(rate); //prints Average; rate.increaseRating(); System.out.println(rate); //prints Good 

thanks

+6
java enums
source share
4 answers

Yes. You can just call

 rate = Rate.Good; 

for this particular case. But I think what you're really looking for is a successor function.

Here you are:

 public class EnumTest extends TestCase { private enum X { A, B, C; public X successor() { return values()[(ordinal() + 1) % values().length]; } }; public void testSuccessor() throws Exception { assertEquals(XB, XAsuccessor()); assertEquals(XC, XBsuccessor()); assertEquals(XA, XCsuccessor()); } } 
+11
source share

Do you need something like this?

 class Rate { private static enum RateValue { VeryBad(1), Bad(2), Average(3), Good(4), Excellent(5); private int rate; public RateValue(int rate) { this.rate = rate; } public RateValue nextRating() { switch (this) { /* ... */ } } } private RateValue value; public void increaseRating() { value = value.nextRating(); } } 
+2
source share

The example in the question tries to change the value of "rate" by calling a method on it. This is not possible, enumeration values ​​are objects, so you cannot change them for the same reasons that you cannot assign a new value to "this". The closest thing you can do is add a method that returns a different enumeration value suggested by Karl Manaster.

+2
source share

It should be possible, but I must admit that I have never tried. At the end of the enumeration, these are simply objects with a slight twist, so you must do this if you do not define the velocity field as final.

-one
source share

All Articles