Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Getting Started with Enumerated Types

By Brett McLaughlin
2005-04-22


Defining an Enum

Listing 2 uses an enumeration to provide similar functionality to Listing 1:
Listing 2. Simple enumerated type

package com.oreilly.tiger.ch03;


public enum Grade {
A, B, C, D, F, INCOMPLETE
};


Here I've used the new keyword enum, given the enum a name, and specified the allowed values. Grade then becomes an enumerated type, which you can use in a manner shown in Listing 3:
Listing 3. Using an enumerated type

package com.oreilly.tiger.ch03;


public class Student {

private String firstName;
private String lastName;
private Grade grade;

public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
return lastName;
}

public String getFullName() {
return new StringBuffer(firstName)
.append(" ")
.append(lastName)
.toString();
}

public void assignGrade(Grade grade) {
this.grade = grade;
}

public Grade getGrade() {
return grade;
}
}
By creating a new enumeration (grade) of the previously defined type, you can then use it like any other member variable. Of course, the enumeration can be assigned only one of the enumerated values (for example, A, C, or INCOMPLETE). Also, notice how there is no error checking code or boundary considerations in assignGrade().

Tutorial Pages:
» Represent Constants in a Typesafe Manner Using Java 5.0
» Defining an Enum
» Working with Enumerated Values
» Enums and Collections
» Going Further
» Use Them, But Don't Abuse Them
» Resources


First published by IBM developerWorks


 | Bookmark
Related Tutorials:
» All about JAXP, Part 1
» Make Database Queries Without the Database
» Load List Values for Improved Efficiency
» 2 Ways To Implement Session Tracking
» A Simple Way to Read an XML File in Java
» Develop Aspect-Oriented Java Applications with Eclipse and AJDT

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources