Other answers are correct, saying that you should implement a default branch that throws an exception in case a new value is added to your enumeration in the future. However, I would like to take one more step and ask why you even use the switch .
Unlike languages like C ++ and C #, Java represents Enum values as real objects, which means you can use object-oriented programming. Let's say that the goal of your method is to provide an RGB value for each color:
switch (color) case RED: return "#ff0000"; ...
Well, perhaps if you want each color to be RGB, you should include this as part of your description:
public enum Color { RED("#FF0000"), BLUE("#0000FF"); String rgb; public Color(String rgb) { this.rgb = rgb; } public getRgb() { return this.rgb; } }
Thus, if you add a new color later, you are largely forced to provide an RGB value. This is even more unsuccessful than the other approach, because you will fail at compile time and not at runtime.
Note that if you need to do even more complex things, including the presence of each color, its own implementation of the abstract method. Enumerations in Java are really powerful and object oriented, and in most cases I have found that in the first place I can avoid the need for a switch .
StriplingWarrior Oct 08 '15 at 16:09 2015-10-08 16:09
source share