Question

In the book Effective Java its told that:

The basic idea behind Java’s enum types is simple: they are classes that export one instance for each enumeration constant via a public static final field. Enum types are effectively final, by virtue of having no accessible constructors.

So, if I have an enum like:

public enum Orange {NAVEL, TEMPLE, BLOOD}

Then, it must be similar to:

public class Orange implements Comparable , implements Serializable {
    private Orange() {}

    public static final Orange NAVEL = new Orange();
    public static final Orange TEMPLE = new Orange();
    public static final Orange BLOOD = new Orange();

    public int compareTo(Orange other) {}
}

To this point it seems fine, but after some time the examples get over complicated, for example I am still puzzled over the following enum definition.

public enum Ensemble {
    SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5),
    SEXTET(6), SEPTET(7), OCTET(8), DOUBLE_QUARTET(8),
    NONET(9), DECTET(10), TRIPLE_QUARTET(12);

    private final int numberOfMusicians;

    Ensemble(int size) {
        this.numberOfMusicians = size;
    }

    public int numberOfMusicians() {
        return numberOfMusicians;
    }
}

What could be its similar class equivalent and is there a length property on it?

Was it helpful?

Solution

The latter example corresponds to a class like this:

public final class Ensemble {
    public static final Ensemble SOLO = new Ensemble(1);
    public static final Ensemble DUET = new Ensemble(2);
    public static final Ensemble TRIO = new Ensemble(3);
    ...
    public static final Ensemble TRIPLE_QUARTET = new Ensemble(12);

    private final int numberOfMusicians;

    private Ensemble(int size) {
        this.numberOfMusicians = size;
    }

    public int numberOfMusicians() {
        return numberOfMusicians;
    }
}
Licensed under: CC-BY-SA with attribution
scroll top