tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Enum > Enum Constructor

Enum Constructor 

The following example shows how to implement custom constructor using enum. All enum types implicitly implements java.io.Serializable and java.lang.Comparable. Here we have defined an enum constructor which accepts direction and distance as constructor parameters. Note that we have overridden toString method to provide our own custom message. Enum provides the following APIs,

public static <E extends Enum<E>> E[] values();
 - Returns all enum constants of this element type. 
 
public final String name()
 - Returns name of enum constant.
 
public final int ordinal()
 - Returns position in its enum declaration starting with index ZERO. 


File Name  :  
com/bethecoder/tutorials/utils/enums/EnumConsTests.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.enums;

enum Direction {

  NORTH("North distance"100),
  SOUTH("South distance"200),
  EAST("East distance"300),
  WEST("West distance"400);
  
  private String name;
  private int distance;
  
  /**
   * Enum constructor.
   
   @param name
   @param distance
   */
  Direction(String name, int distance) {
    this.name = name;
    this.distance = distance;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getDistance() {
    return distance;
  }

  public void setDistance(int distance) {
    this.distance = distance;
  }

  public String toString() {
    return getName() "[" + getDistance() "KM] "  + name() " [" + ordinal() "]";
  }
}

public class EnumConsTests {

  /**
   @param args
   */
  public static void main(String[] args) {

    Direction [] directions = Direction.values();
    
    for (int i = ; i < directions.length ; i ++) {
      System.out.println(directions[i]);
    }
    
  }
  
}
   

It gives the following output,
North distance[100KM] NORTH [0]
South distance[200KM] SOUTH [1]
East distance[300KM] EAST [2]
West distance[400KM] WEST [3]



 
  


  
bl  br