Pages

Sunday, June 10, 2012

Enum classes


The enum classes are used to enumerated multiple secuential values with its names. Those values are statics, and can be accessed publicly. 

Example:
public enum Week{
MONDAY, //numeric value = 0
TUESDAY, //numeric value = 1
WEDNESDAY, //numeric value = 2
THURSDAY, //numeric value = 3
FRIDAY, //numeric value = 4
SATURDAY, //numeric value = 5
SUNDAY //numeric value = 6
}

Apart of this, the enum class can have variables and methods as other classes. When there are some variables in the enum class, those variables will be linked to the enum values. Thus, the enum values can be setted as you want. Here is another example:

Code:
public enum Bottle{
 LITTLE (250), MEDIUM (500), BIG (1500);
 private int ml;
 public Bottle (int size){
  this.ml = size;
 }
 public int getSize(){
  return this.ml;
 }
}
public class Pack{
 private int nBottles;
 private Bottle bottleSize;
 public Pack (int nBottles, Bottle bottleSize){
  this.nBottles = nBottles;
  this.bottleSize = bottleSize;
 }
 public int getNBottles(){ return this.nBottles; }
 public Bottle getBottleSize() { return this.bottleSize; }
 public static void main(String[] args){
  Pack p = new Pack(6, Bottle.BIG);
  System.out.println("This is a pack of " + p.getNBottles() + " bottles.");
  System.out.println("Each " + p.getBottleSize() + " bottle has " + p.getBottleSize().getSize() + " ml.");
 }
}
Output:
This is a pack of 6 bottles.
Each  BIG bottle has 1500 ml.

No comments:

Post a Comment