Thursday, August 12, 2010

Enumerate it!

Today I will write about really cool thing in Java that is enum type. If you used to code in C/C++ you may wonder what is so cool about it since it's really simple and straightforward. Well, in Java things are a little bit different. Of course, you can use enums in the way that you know from C, for example:
 enum Colour {RED, YELLOW, BLUE}

but that's not really what I'm gonna cover here. Enums in Java are much more than that. They are some kind of a class so you can actually add constructors, instance variables, methods and one more thingy.
Let's say that you would like somehow associate the enum value with a string that says something more about the colour. We can do it in this way:
 enum Colour {
RED("bloody"), YELLOW("shiny"), BLUE("sea");
String info;
Colour(String info) {
this.info = info;
}
}
public class Woo {
public static void main(String[] args) {
for(Colour c: Colour.values()) {
System.out.println(c.info + " " + c);
}
}
}

So in the above code we define our Colour enum. It is different from the previous example from the very beginning - we define our values but in brackets we put our additional information. This can happen because later on we define a constructor that can handle this. We also define a "info" field to which, the constructor will pass given reference. In the main() function we also use the static method of enum's values() which returns an array of previously defined enums. Please note that the order is exactly the same as in the definition.

Alright, at the beginning I mentioned some enum's features and among others there was some thingy thing. In fact, what I meant is constant specific class body. To explain it, imagine that you would like to even add some more information about the colours and that the only thing you can say more about them is "mmm..." (cause they're so good so you'd like to hoover'em) except the BLUE one. With the blue you would like to say add "extreamly". To cope with it we can define a method that will return the string consisting of "extreamly". But wait! We don't want to get the same information for all enums. In case of the BLUE we want to have "extreamly". And here comes constant specific class body where we can override the method and make it specific to the chosen enum value. The important thing here is that it can be only used for overriding the methods defined in the enum. If there is no method in the enum, you can put any in the constant specific class body.
And here is the code for the example just described:
 enum Colour {
RED("bloody"),
YELLOW("shiny"),
BLUE("sea") {
public String moreInfo() {
return "extreamly";
}
};
String info;
Colour(String info) {
this.info = info;
}
public String moreInfo() {
return "mmm...";
}
}
public class Woo {
public static void main(String[] args) {
for(Colour c: Colour.values()) {
System.out.println(c.moreInfo() + " " + c.info + " " + c);
}
}
}

No comments:

Post a Comment