Time to open the Champagne -- Java 1.5 is out, and the language has finally come of age! With the new Java 1.5 specification, Java now contains features that make it feel like a proper "grown-up" language. The rest of this article will introduce you to these new features. To try out the features for yourself, simply download Java 1.5 from Sun’s website and give it a whirl. Note that you’ll need to compile the code using the –source 1.5 option; otherwise, you’ll get compilation errors when using the new features.
This makes all the values defined for CardSuit and CardValue available to the importing class as if they were defined in the same class. For example:
Card sixHearts
= new Card(six, hearts);
Static imports can be used to import static identifiers and static methods as well as enumerations.
Generics
Something that I always found irksome about Java was the difference in the strength of typing between arrays and collections. If an array of objects is used to hold some data, then every object in the array has to be a (direct or indirect) instance of the same class. Any attempt to assign an object of some other class to an element of the array results in a compile-time error. On the other hand if a collection is used in Java 1.4 or earlier, then it is a (weakly-typed) collection of objects. This means that assigning an object of some other class to an element of the collection is perfectly acceptable to the compiler, even though it may not have been the intention of the programmer. Such situations give rise to a run-time error (typically a ClassCastException). In other words, the use of collections placed an additional burden on the programmer to avoid run-time errors that could not occur when arrays were used. The programmer was faced with a trade-off between the flexibility of collections and the type-safety of arrays. The good news is that this trade-off no longer exists! From Java 1.5, collections can be strongly typed.
Instead of saying:
List deck
= new ArrayList();
and (at most) commenting the intention that the List is to contain only objects of the class Card, we can now enforce that constraint programmatically:
List
<Card> deck = new ArrayList<Card>();
There is much more to be said about generics than can be covered in this article, but the basic idea should be clear. For more information, take a look at Sun's Generics Tutorial.