Archive

Posts Tagged ‘enum’

Enums are classes too. Neat

September 29, 2009 Leave a comment

Got this from Effective Java, which I would strongly urge anyone to read before they write production code in Java.

Copied from here

Eg:

public enum Direction {
    NORTH { public Direction getOpposite() { return SOUTH; }},
    EAST { public Direction getOpposite() { return WEST; }},
    SOUTH { public Direction getOpposite() { return NORTH; }},
    WEST { public Direction getOpposite() { return EAST; }};

    public abstract Direction getOpposite();
}

Also possible

public interface Direction {
    public Direction getOpposite();
};

public enum ValidDirection implements Direction {
    NORTH { public Direction getOpposite() { return SOUTH; }},
    EAST { public Direction getOpposite() { return WEST; }},
    SOUTH { public Direction getOpposite() { return NORTH; }},
    WEST { public Direction getOpposite() { return EAST; }};
}

PS: WordPress has changed a LOT over the year!

Advertisements
Categories: Java, Technology Tags: , , ,