Wednesday, April 13, 2011

Constant specific methods for enums

If the implementation of methods vary for each Constant, then you can implement the methods specific to a constant.

public enum Color {
RED { public Color complimentary() { return GREEN; }},
BLUE { public Color complimentary() { return ORANGE; }},
YELLOW { public Color complimentary() { return PURPLE; }},
...

public abstract Color complimentary();
}


Each color has its own complementary color and to implement this we can use constant specific methods to return the complementary color. The method complementary() has to be either defined as an abstract method within Color enum or could be a method in one of the implemented interfaces.

No comments:

Post a Comment

Chitika