|
Wildcard Instantiations of Parameterized Types
Use wildcards to permit type declarations, courtesy of the Java Generics language construct in the upcoming release of J2SE 1.5
by Klaus Kreft and Angelika Langer
Posted May 12, 2004
Editor's Note: This is part 1 of a two-part article that explains the purpose and use of the wildcards language construct in Java Generics, an important feature available in J2SE 1.5 that is slated for full release later this year. Part 2 will cover using wildcard instantiations and looks at some of their limitations.
With the upcoming release of J2SE 1.5 (expected to be announced in August 2004) parameterized types and methods, also known as Java Generics, will be available as a new language feature of the Java programming language. We provided an overview of most of the Java Generics features previously in a two-part discussion beginning with "Language Features of Java Generics" (Java Pro Online, March 3, 2004) and the conclusion in "Implementing Java Generics" (Java Pro Online, March 10, 2004).
Here we'll explain wildcards, which form another language construct relevant in the context of Java Generics. Wildcards can be used for instantiation of parameterized types. In its simplest form a wildcard is a question mark (?) and permits type declarations such as List<?>, for example.
What is the purpose of wildcards? Consider a hierarchy of shape classes with an abstract superclass Shape and several subclasses such as Circle, Triangle, Rectangle, and so on. All shape classes have a draw() method:
public abstract class Shape {
public abstract void draw();
}
public final class Circle {
...
public void draw() { ... }
...
}
public final class Triangle {
...
public void draw() { ... }
...
}
...
Given a collection of shapes we might want to implement a drawAllShapes() method. How would we declare this method? Here is a first approach:
public void drawAllShapes(
Collection<Shape> c) {
for (Shape s : c) {
s.draw();
}
}
Note that we've been using the enhanced for-loop syntax, which is another new feature in Java 1.5. An expression such as:
for (Shape s : c) { s.draw(); }
is a shorthand notation for:
for (Iterator _i = c.iterator();
_i.hasNext(); ) { Shape s =
_i.next(); s.draw(); }
Back to top
|