Getting Started with Enumerated Types
By Brett McLaughlin2005-04-22
Defining an Enum
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;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().
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;
}
}
Tutorial pages:
|
First published by IBM developerWorks
|
|||||||||
You might also want to check these out:
|
Leave a Comment on "Getting Started with Enumerated Types"
You must be logged in to post a comment.
Link to This Tutorial Page!

