Enumeration

Below we have 3 objects (aka enumerations in this case), and they each have their own set of variables. One for description, and one for year. Enumerations are effectively objects that are also constants.

When we use enumeration, java automatically creates an array of the values, this array is cat.values()

// jamesprogram.java
class jamesprogram {

	public static void main (String[] args){
		
		// enhanced for loop
		// this loops through the enumeration
		// contants in the array cat.values() and
		// assign them to people
		for (cat people: cat.values()){
			
			System.out.printf("%s\t%s\t%s\n", people, people.getDesc(), people.getYear());
		}
	}
}
//cat.java
// the enum allows us to use the class in
// a specific way
public enum cat {
	
	// declare constants of the enum type
	// i.e. variables that never change
	james("java","37"),
	emma("xml","40"),
	george("php","100");
	
	// final, we don't want this changed
	// these two declared variables represent
	// the two arguments above
	private final String desc;
	private final String year;
	
	//now have a enumeration constructor
	cat(String description, String theirYear){
		desc = description;
		year = theirYear;
	}
	
	public String getDesc(){
		return desc;
	}
	
	public String getYear(){
		return year;
	}
	
}

Outputs:

james java 37
emma xml 40
george php 100

Leave a Reply