Java Reference
In-Depth Information
public <ViewerType> void showTo(ViewerType viewer)
{
System.out.println("Hello " + viewer);
System.out.println("Data is " + data);
}
...
}
Note that T and ViewerType are different type parameters. T is a type parameter for the
entire class, but ViewerType is a type parameter only for the method showTo . Below is
a sample use of these generic methods:
Sample<Integer> object = new Sample<Integer>(42);
object.<String>showTo("Friend");
This produces the output:
Hello Friend
Data is 42
Inheritance with Generic Classes
You can define a generic class to be a derived class of an ordinary class or a derived
class of another generic class. Display 14.11 contains the definition of a generic class
called UnorderedPair , which is a derived class of the generic class Pair (which we
gave in Display 14.5). The class UnorderedPair overrides the definition of equals
that it inherits from Pair . To a programmer using the class, UnorderedPair is just like
the class Pair with one exception. In UnorderedPair , the two components do not
have to be in the same order for two pairs to be equal. Less formally, in the
Pair<String> world, "beer" and "peanuts" is not the same as "peanuts" and "beer" .
In the UnorderedPair<String> world, they are the same. This is illustrated by the
demonstration program in Display 14.12.
Just as you would expect, an object of type UnorderedPair<String> is also of type
Pair<String> . As we have seen so far, inheritance with generic classes is straightforward in
most cases. However, there are some situations with subtle pitfalls. We discuss those next.
Display 14.11 A Derived Generic Class (part 1 of 2)
1 public class UnorderedPair<T> extends Pair<T>
2{
3
public UnorderedPair()
4
{
5
setFirst( null );
6
setSecond( null) ;
7
}
8
public UnorderedPair(T firstItem, T secondItem)
9
{
Search WWH ::




Custom Search