Some reader favorites:
EJB fundamentals and session beans
Create a scrollable virtual desktop in Swing
Wizard API updated!
Tim Boudreau has released a new version of the Swing Wizard library (version 0.997) that fixes the WizardException bug reported in JavaWorld's recent Open Source Java Project profile. The article's examples have been reworked to test out the new, improved WizardException. Thanks, Tim, for this helpful fix!
Open Source Java Projects: The Wizard API
Using enumerated constants can make code more readable. For example, you might want to define a new data type named Color with constants RED, GREEN, and BLUE as its possible values. The idea is to have Color as an attribute of other objects you create, such as Car objects:
class Car {
Color color;
...
}
Then you can write clear, readable code, like this:
myCar.color = RED;
instead of something like:
myCar.color = 3;
An even more important attribute of enumerated constants in languages like Pascal is that they are type safe. In other words, it is not possible to assign an invalid color to the color attribute -- it must always be either RED, GREEN, or BLUE. In contrast, if the color variable were an int, then you could assign any valid integer to it, even if that number did not represent a valid color.
This article gives you a template for creating enumerated constants that are:
In a future article, you will learn how to extend enumerated constants to implement state-dependent behavior.
static final int RED = 0; static final int GREEN = 1; static final int BLUE = 2; ...
Static finals are useful
Because they are final, the values are constant and unchangeable. Because they are static, they are only created once for
the class or interface in which they are defined, instead of once for every object. And because they are integer variables,
they can be enumerated and used as an index.
For example, you can write a loop to create a list of a customer's favorite colors:
for (int i=0; ...) {
if (customerLikesColor(i)) {
favoriteColors.add(i);
}
}
You can also index into an array or a vector using the variables to get a value associated with the color. For example, suppose
you have a board game that has different colored pieces for each player. Let's say you have a bitmap for each color piece
and a method called display() that copies that bitmap to the current location. One way to put a piece on the board might be something like this:
PiecePicture redPiece = new PiecePicture(RED); PiecePicture greenPiece = new PiecePicture(GREEN); PiecePicture bluePiece = new PiecePicture(BLUE);
void placePiece(int location, int color) { setPosition(location); if (color == RED) { display(redPiece); } else if (color == GREEN) { display(greenPiece); } else { display(bluePiece); } }
But by using the integer values to index into an array of pieces, you can simplify the code to:
PiecePicture[] piece = {new PiecePicture(RED),
new PiecePicture(GREEN),
new PiecePicture(BLUE)
};
void placePiece(int location, int color) {
setPosition(location);
display(piece[color]);
}
Being able to loop over a range of constants and index into an array or vector are the major advantages of static final integers. And when the number of choices grows, the simplification effect is even greater.
But static finals are risky
Still, there are a couple of drawbacks to using static final integers. The major drawback is the lack of type safety. Any
integer that is calculated or read in can be used as a "color," regardless of whether it makes sense to do so. You can loop
right past the end of the defined constants or stop short of covering them all, which can easily happen if you add or remove
a constant from the list but forget to adjust the loop index.
For example, your color-preference loop might read like this:
for (int i=0; i <= BLUE; i++) {
if (customerLikesColor(i)) {
favoriteColors.add(i);
}
}
Later on, you might add a new color:
static final int RED = 0; static final int GREEN = 1; static final int BLUE = 2; static final int MAGENTA = 3;
Or you might remove one:
static final int RED = 0; static final int BLUE = 1;
In either case, the program will not operate correctly. If you remove a color, you will get a runtime error that draws attention to the problem. If you add a color, you won't get any error at all -- the program will simply fail to cover all of the color choices.
Another drawback is the lack of a readable identifier. If you use a message box or console output to display the current color choice, you get a number. That makes debugging pretty difficult.
The problems creating a readable identifier are sometimes solved using static final string constants, like this:
static final String RED = "red".intern(); ...
Using the intern() method guarantees there is only one string with those contents in the internal string pool. But for intern() to be effective, every string or string variable that is ever compared to RED must use it. Even then, static final strings
do not allow for looping or for indexing into an array, and they still do not address the issue of type safety.
An elegant solution was provided in Philip Bishop's article in JavaWorld, "Typesafe constants in C++ and Java."
The idea is really simple (once you see it!):
public final class Color { // final class!!
private Color() {} // private constructor!!
public static final Color RED = new Color();
public static final Color GREEN = new Color();
public static final Color BLUE = new Color();
}
Because the class is defined as final, it can't be subclassed. No other classes will be created from it. Because the constructor is private, other methods can't use the class to create new objects. The only objects that will ever be created with this class are the static objects the class creates for itself the first time the class is referenced! This implementation is a variation of the Singleton pattern that limits the class to a predefined number of instances. You can use this pattern to create exactly one class any time you need a Singleton, or use it as shown here to create a fixed number of instances. (The Singleton pattern is defined in the book Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides, Addison-Wesley, 1995. See the Resources section for a link to this book.)
Free Download - 5 Minute Product Review. When slow equals Off: Manage the complexity of Web applications - Symphoniq
![]()
Free Download - 5 Minute Product Review. Realize the benefits of real user monitoring in less than an hour. - Symphoniq