Nice TWiki > Dev > EnumImplementation (r1.7 vs. r1.8) TWiki webs:
Dev | Doc | Main | TWiki | Sandbox
Dev . { Changes | Index | Search | Go }
 <<O>>  Difference Topic EnumImplementation (r1.8 - 16 Jan 2005 - MotiN)
Added:
>
>


I saw an implementation like the following a while ago, which I think does it quite nicely. Consider it as a pattern to be generate when ever an enum is specified:

final public class Coin {

    public final static Coin PENNY   = new Coin("Penny");
    public final static Coin NICKEL  = new Coin("Nickel");
    public final static Coin DIME    = new Coin("Dime");
    public final static Coin QUARTER = new Coin("Quarter");

    final String name;

    private Coin(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

An example of usage:
Coin aPenny = Coin.PENNY; // ok
Coin aHalfDollar = new Coin("HalfDollar"); // fails due to private constructor

This has some advantages in that one can't add on to a declared enum, code is readable, equals(), hashCode(), and == operator (i.e. identity) work nicely, as does toString(). Of course, it's type-safe too. On the downside, it depends on access modifiers, which don't exist yet in Nice (but will be implemented, of course).

If one wants to associate values with the enum, then this implementation is no good, of course. Though one could probably handle that by changing from what one generates the resulting code to be like in the Java 1.5 spec and then generate the following:

final public class Coin {

    public final static Coin PENNY   = new Coin("Penny", 1);
    public final static Coin NICKEL  = new Coin("Nickel", 5);
    public final static Coin DIME    = new Coin("Dime", 10);
    public final static Coin QUARTER = new Coin("Quarter", 25);

    private final String name;
    private final int value;

    private Coin(String name, int value) {
        this.name = "Coin." + name; // replace "Coin." with fully qualified class name perhaps. or eliminate (?)
        this.value = value;
    }

    public String toString() {
        return name;
    }

    public int value() {
        return value;
    }
}

-- MotiN - 16 Jan 2005


Topic EnumImplementation . { View | Diffs | r1.8 | > | r1.7 | > | r1.6 | More }
Revision r1.7 - 22 Feb 2004 - 19:34 GMT - BrianSmith
Revision r1.8 - 16 Jan 2005 - 15:22 GMT - MotiN
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.