Java Reference
In-Depth Information
Listing 15-2. A Simplified Generic
LinkedList<JPanel> panelList = new LinkedList<>();
Notice that the constructor for our LinkedList object indicates that it's a generic but doesn't provide
the type of the objects that can go in the list. We can leave that out because the compiler can infer a type
of JPanel from the type declaration portion of this variable declaration. By the way, the <> expression is
often called “the diamond.”
An object can have multiple parameters, provided a matching class exists to define that object.
Listing 15-3 shows an example.
Listing 15-3. A Generic with Multiple Parameters
package com.bryantcs.examples;
public class GenericRole<Actor, Role> {
private Actor actor;
private Role role;
public GenericRole(Actor p, Role a) {
actor = p;
role = a;
}
public Actor getActor() {
return actor;
}
public Role getRole() {
return role;
}
}
A significant feature of this class is that you do not have to create an Actor class or a Role class.
Because it uses generics, the declarations that create instances of the GenericRole object must specify
the types of the Actor and Role objects.
As I mentioned at the beginning of this section, this arrangement is where the word “generic” comes
from. These objects can be undeclared at this point, so they are, in a sense, generic.
So let's look at a class that does something with our GenericRole class. Consider Listing 15-4.
Listing 15-4. Using a Multiple-Parameter Generic
package com.bryantcs.examples;
import java.util.LinkedList;
public class GenericRoleProgram {
Search WWH ::




Custom Search