a few words at the beginning
Today we will take a look at Enums in Java. Let's start with a definition:
Enumeration - a collection of items that is a complete, ordered listing of all of the items in that collection.
Sounds simple isn't it? Even if, Enums in Java allows us for many things and it's a really great language's feature, which can increase quality of our code.Today I will highlight only the basics of enumeration and more will come in next post.
Type-safe
This mean your enum will have a type and you can not assign any value other than specified in Enum constants.To be more specific, with following enum:
enum Season { SPRING, SUMMER, AUTUMN, WINTER }there is no problem to write something like:
Season favouriteSeason = Season.SUMMER;but:
Season favouriteSeason = 1;will end up with:
java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to Season
own namespace
Which means that even if values in one enumeration overlaps with other enum:enum TDDStep { RED, GREEN, REFACTOR } enum TrafficLight { RED, ORANGE, GREEN }Both are valid and can be used concurrently.
constants are implicitly static and final
It's impossible to do something like:TDDStep.RED = TDDStep.GREEN;It will just end up with:
java.lang.Error: Unresolved compilation problem: The final field TDDStep.RED cannot be assigned
usable inside a switch statement.
So don't be afraid of writing something like this:public void continueWork(TDDStep step) { switch (step) { case RED: makeTestGreen(); break; case GREEN: refactoreCode(); break; case REFACTOR: goToNextTest() break; } }It will work :) As well in code as in your real life :)
can not create instance by using new
As it's written in documentation:
The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
And this is (according to definition) because the Enum should be the only one responsible for returning the predefined instances.To prevent any other modification:
The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.
But if you would like to try anyway, you will get:
java.lang.Error: Unresolved compilation problem: Illegal modifier for the enum constructor; only private is permitted.
That's all for today, hopefully you liked it and don't worry - more fun is in front of you and will come soon :)
No comments:
Post a Comment