Java & J2EE Page 3 - Java Comes of Age |
Static Import If you take exception to such lengthy references, in Java1.5 you can now use a static import:
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:
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:
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:
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.
blog comments powered by Disqus |