mercredi 31 octobre 2012
mercredi 13 juin 2012
When I was learning Java at my university, the java version used was 1.4. Since then, the language has evolved I had to update myself with the new features that was added to the language.One day, I passed a skill test in Java that I totally failed. One of the questions was about enums and I was always thought that the enums in C and Java were similar. I was totally wrong.
Here is what I found.
Declaring and using an enum in Java is very simple :
It's not required to put a semicolon after the enum declaration.
Enums can be declared as their own separate class, or as a class member, however they must not be declared within a method. Base on our previous example, it's totally legal to create a file named Color.java and declare my enums constants in this file. We could already conclude that enums are special kind of class.
The basic component of an enum are its constants. But contrary to the language C, enums constants are not integers or Strings. In fact, the constants are objects and their type is the type of the enum declaration. Which means, RED is an instance of Color, as for GREEN, BLUE, etc. So, this code is completely legal :
System.out.println(mycolor.color instanceof Color);
Think of an enum as a kind of class. Our previours code sample could be written like this (but it's not totally right) :
Notice that every constant in our enum (RED, GREEN, BLUE, etc) are instances of type Color. They are represented as static and final which in the Java world is thought of as a constant. Also notice that each enum value knows its index or position, in other words, the order in which enums values are declared matters.
Because enum is a special kind of class, you can add constructors, methods, instances variables and something really strange called specific class body.
Imagine that we would like to represent every color in our enum with their RGB code.
The method values() is a static method that returns an array of the enum's value in the order they are declared.
Some key points about constructors :
- You can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments you define after the constant value. For example, RED(255,0,0) invokes the Color constructor that takes 3 int and passing the 255,0,0 literals to the constructor.
- You can define many arguments to our constructors and you can also overload the enum constructors.
Let's add toString() method in our enum (remember that an enum is a special kind of class in Java) and we will redefine the toString method for the white color and black color in our application. Here is the code :
Java gives us the possibility override a method defined in the enum for a particular constant. It's like an anonymous inner class and it's called a specific class body. In our example, the WHITE and BLACK constants overrides the toString() method.