For those who lure here by name: yes, you can define your own methods in enum. If you are interested in how to call such a non-static method, you do it the same way as any other non-static method - you call it in an instance of the type that defines or inherits this method. In the case of transfers, such instances are simply ENUM_CONSTANT .
So all you need is EnumType.ENUM_CONSTANT.methodName(arguments) .
Now let's get back to the issue from the question. One solution might be
public enum Direction { NORTH, SOUTH, EAST, WEST; private Direction opposite; static { NORTH.opposite = SOUTH; SOUTH.opposite = NORTH; EAST.opposite = WEST; WEST.opposite = EAST; } public Direction getOppositeDirection() { return opposite; } }
Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH .
Here's a slightly more βhackyβ way to illustrate @ jedwards comment, but itβs not as flexible as the first approach, since adding more fields or changing their order will break our code.
public enum Direction { NORTH, EAST, SOUTH, WEST; // cached values to avoid recreating such array each time method is called private static final Direction[] VALUES = values(); public Direction getOppositeDirection() { return VALUES[(ordinal() + 2) % 4]; } }
Pshemo Sep 18 '13 at 23:01 2013-09-18 23:01
source share