Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 85
نمايش فراداده

8.3 Importing Enumerated Type Values

The next natural thought in working with static imports is to use them in conjunction with another Tiger feature, enumerated values (detailed in Chapter 3). Since the compiler declares enumerated values as public, static, and final, they are great candidates for being statically imported.

8.3.1 How do I do that?

Remember that enums are just a specialized type of Java class. As a result, the syntax to use them is no different than what you've already seen. Chapter 3, and then uses them in a simple program.

Example 8-2. Importing enum values
package com.oreilly.tiger.ch08;
import static java.lang.System.out;
import static com.oreilly.tiger.ch03.Grade.*;
import java.io.IOException;
import java.io.PrintStream;
import com.oreilly.tiger.ch03.Student;
public class EnumImporter {
private Student[] students = new Student[4];
public EnumImporter( ) {
students[0] = new Student("Brett", "McLaughlin");
students[0].assignGrade(A);
students[1] = new Student("Leigh", "McLaughlin");
students[0].assignGrade(B);
students[2] = new Student("Dean", "McLaughlin");
students[0].assignGrade(C);
students[3] = new Student("Robbie", "McLaughlin");
students[0].assignGrade(INCOMPLETE);
}
public void printGrades(PrintStream out) throws IOException {
for (Student student : students) {
if ((student.getGrade( ) == INCOMPLETE) ||
(student.getGrade( ) == D)) {
// Make this student retake this class
}
}
}
public static void main(String[] args) {
try {
EnumImporter importer = new EnumImporter( );
importer.printGrades(out);
} catch (Exception e) {
e.printStackTrace( );
}
}
}

NOTE

Dean and Robbie appear to be spending too much time playing guitar and banjo, and not enough time studying!

Nowhere in this class do you see Grade.A or Grade.INCOMPLETE, which really reduces the overall clutter. As a result, the code is a good deal clearer, and even a little shorter (not a bad thing).

This same trick works for enums that are declared inline within a class; remember the Downloader example from Chapter 3? It's reprinted here for convenience:

package com.oreilly.tiger.ch03;
public class Downloader {
public enum DownloadStatus { INITIALIZING, IN_PROGRESS, COMPLETE };
// Class body
}

You can import these into another class with the following line:

     import static com.oreilly.tiger.ch03.Downloader.DownloadStatus.*;

As I mentioned back in Chapter 3, though, this is more of a hack than a real programming solution. If you need an enum in more than one class, it's a better practice to define the enum separately (in it's own .java file), and then use it in both classes, rather than tying its declaration into a particular class file.