Re: Named fields in enum constant declarations
Joshua Cranmer wrote:
Patricia Shanahan wrote:
What am I missing? What is the right way to do this?
public enum Visualization {
TRUE_POSITIVE(ColorConstants.LIGHT_GREEN);
private static class ColorConstants {
static final Color LIGHT_GREEN = new Color(100, 255, 100);
}
Visualization(Color c) {}
}
That seems the best way to me. Unfortunately, you can't put the static
class before the constants.
There can only be one top-level public class per source file, but there
can be more than one top-level class. Does the public one (where there
is one) need to be first, and can there be back-references among them?
If the answers are "no" and "yes" in that order, you might be able to use:
class ColorConstants {
static final Color LIGHT_GREEN = new Color(100, 255, 100);
}
public enum Visualization {
TRUE_POSITIVE(ColorConstants.LIGHT_GREEN);
private Color col;
Visualization(Color c) { col = c; }
}
which puts the color constants above the enum constants. On the other
hand, it puts the actual declaration of Visualization in
Visualization.java lower in the file than normal, and maybe "below the
fold" in your editor/IDE.
On the gripping hand, I don't personally see a big problem with
public enum Visualization {
TRUE_POSITIVE(new Color(100,255,100));
private Color col;
Visualization(Color c) { col = c; }
}
since the color is part of a constant declaration anyway (the enum
constant's) and magic numbers in constant declarations are kosher.