Wednesday, July 13, 2016

Enums in Java

If you're familiar with C or C++, you may tend to think of enums as just integers. Which they basically are - in those languages, but not in Java.
Java enum is a special kind of class. What's the difference for you as a user?

It you just want a simple enum and don't care about real values behind enum constants, you can go ahead and just do as in old good C (almost, as C syntax is slightly different):
enum Color {RED, GREEN, YELLOW}
 . . .
Colors col = RED;
But if you try to assign an integer value to col, as you could in C, like so:
col = 2;
- the code fails to compile, which is a good thing, as you obviously want your value to be one of the predefined constants.
Well, actually you can't compile this in C++ either, but you can still force the compiler to build it by using a cast like this one:
col = (Color)2;
But that's beside the point. If you want your constants to have specific values, in C you could achieve that like this (note that this is C syntax, which is slightly different from Java):
enum Color {RED=5, YELLOW=10, GREEN=15};
If you want this in Java, you have to take into account that your enum is going to be a special kind of Java class, extending java.lang.Enum. Its syntax is also different from both C / C++ enums and normal Java classes:
enum Color
{
    RED(5), GREEN(10), YELLOW(15);
    private int col;
    private Color(int col) { this.col = col; }
    private int getValue() { return col; }
}
And this is how you use it:
Color c = Color.RED;
System.out.println(c);
which prints out
RED
But you can't just go and assign an integer value to your enum object:
Color c = 5;
System.out.println(c);
because
error: incompatible types: int cannot be converted to Color

There's much more to Java enums, check out these links for more details:

No comments:

Post a Comment