Using methods and static blocks

suggest change

An enum can contain a method, just like any class. To see how this works, we’ll declare an enum like this:

public enum Direction {
    NORTH, SOUTH, EAST, WEST;
}

Let’s have a method that returns the enum in the opposite direction:

public enum Direction {
    NORTH, SOUTH, EAST, WEST;

    public Direction getOpposite(){
        switch (this){
            case NORTH:
                return SOUTH;               
            case SOUTH:
                return NORTH;                
            case WEST:
                return EAST; 
            case EAST:
                return WEST;  
            default: //This will never happen
                return null;
        }
    }
}

This can be improved further through the use of fields and static initializer blocks:

public enum Direction {
    NORTH, SOUTH, EAST, WEST;
    
    private Direction opposite;
    
    public Direction getOpposite(){
        return opposite;
    }
    
    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        WEST.opposite = EAST;
        EAST.opposite = WEST;
    }
}

In this example, the opposite direction is stored in a private instance field opposite, which is statically initialized the first time a Direction is used. In this particular case (because NORTH references SOUTH and conversely), we cannot use Enums with constructors here (Constructors NORTH(SOUTH), SOUTH(NORTH), EAST(WEST), WEST(EAST) would be more elegant and would allow opposite to be declared final, but would be self-referential and therefore are not allowed).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents