Tuesday, January 13, 2015

Deeper understand of Enum in Java

Reference:
http://howtodoinjava.com/2012/12/07/guide-for-understanding-enum-in-java/
Enumerations (in general) are generally a set of related constants. Each constant represents a specific instance of its Enumerations class. For example:

public enum DIRECTION {
     EAST,
     WEST,
     NORTH,
     SOUTH        //optionally can end with ";"
 }
 
Here EAST, WEST, NORTH and SOUTH are final static inner classes of Direction of type Direction extends java.lang.Enum.

Enums are comparable and serializable implicitly. Also, all enum types in java are singleton by default. So, you can compare enum types using ‘==’ operator.

You can give define your own constructors to initialize the state of enum types.
enum Direction {
    // Enum types
    EAST(0), WEST(180), NORTH(90), SOUTH(270);
 
    // Constructor
    private Direction(final int angle) {
        this.angle = angle;
    }
 
    // Internal state
    private int angle;
 
    public int getAngle() {
        return angle;
    }
}
 
 
Use template methods in enum:
 
package enumTest;
public enum Direction {
    // Enum types
    EAST(0) {
        <strong>@Override</strong>
        public void shout() {
            System.out.println("Direction is East !!!");
        }
    },
    WEST(180) {
        @Override
        public void shout() {
            System.out.println("Direction is West !!!");
        }
    },
    NORTH(90) {
        @Override
        public void shout() {
            System.out.println("Direction is North !!!");
        }
    },
    SOUTH(270) {
        @Override
        public void shout() {
            System.out.println("Direction is South !!!");
        }
    };
    // Constructor
    private Direction(final int angle) {
        this.angle = angle;
    }
 
    // Internal state
    private int angle;
 
    public int getAngle() {
        return angle;
    }
 
    <strong>// Abstract method which need to be implemented</strong>
    public abstract void shout();
}
 
 

No comments:

Post a Comment