Enums

From Suhrid.net Wiki
Revision as of 01:00, 25 June 2011 by Suhridk (talk | contribs)
Jump to navigationJump to search
  • Enums are a feature that allows a variable to be restricted to having only a few predefined values.
  • Type-safe in built alternative as opposed to representing constants with integers or creating enum patterns.
  • e.g. if we want to restrict a variable that represents t-shirt sizes and colors to only one of four possible sizes, we can use an enum:
enum TShirtSize {
     S,M, L, XL
};

enum TShirtColor {
	RED, BLACK, BLUE, WHITE;
}

public class TShirt {
	
	private TShirtSize size;
	private TShirtColor color;
	
	public TShirt(TShirtSize size, TShirtColor color) {
		this.size = size;
		this.color = color;
	}
	
	public String toString() {
		return size + ","  + color;
	}
	
	public static void main(String[] args) {
		
		TShirt t1 = new TShirt(TShirtSize.M, TShirtColor.RED);
		System.out.println(t1); //Will print: M, RED;
		TShirt t2 = new TShirt(TShirtSize.L, TShirtColor.WHITE);
		System.out.println(t2); //Will print: L, WHITE;
	}

}
  • Enum instances are instances of the enum type. Like instances of any class.

Declaration

  • Enums behave like non-inner classes.
  • Enum can be declared ONLY with public or default modifier (like a non-inner class).
  • If they are made public - they must be in their own file (like public classes).
  • Cannot be declared within methods.
  • Enums can have constructors, variables and methods like a regular class. (But they have to be declared in a specific way)
  • The constants must be specified in the beginning, before anything else.
  • For e.g. if we want to specify inches for the T-Shirt Size
enum TShirtSize {
	
	S(38), 
	M(40), 
	L, //Uses the default constructor
	XL(44); 
	
	private int inches;
	
	TShirtSize() {
		
	}
	
	TShirtSize(int inches) {
		this.inches = inches;
	}
	
	public int getInches() {
		return inches;
	}
	
};

class TShirt {
   void foo() {
       TShirtSize size = TShirtSize.M;
       System.out.println(size.getInches()); //Prints 40;
   }
}

Constant specific class body

  • Works like anonymous inner classes.
  • Situation where we need to oveerride the regular behaviour of an enum, for a specific constant.
  • Example:
enum TShirtSize {
	
	S(38), 
	M(40), 
	L(42) {
		public int getInches() {
			if(Locale.getDefault().equals(Locale.US)) {
				return 44;
			} else {
				return 42;
			}
		}
	},
	XL(44);
	
	private int inches;
	
	TShirtSize() {
		
	}
	
	TShirtSize(int inches) {
		this.inches = inches;
	}
	
	public int getInches() {
		return inches;
	}
	
};