It seems that many examples of Java Generics fail to show the generic capabilities of this feature. In the code below, I first use the class
Line to represent a geometric
line and then as a
line that Leisure Suit Larry might use in a bar. You can see the result of running the code in red, below.
import java.util.*;
import static java.lang.System.out;
public class Line {
T start;
T end;
public void print() {
out.println( start + " ... " + end );
}
public Line(T a, T b) {
start = a; end = b;
}
public static void main(String[] args) {
Line.Point p1 = new Line.Point( 1, 1 );
Line.Point p2 = new Line.Point( 2, 2 );
Line j = new Line( p1, p2 );
j.print();
//
String intro = "Wow, you look HOT!";
String pickup = "What's your sign?";
Line getGirl = new Line( intro, pickup );
getGirl.print();
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x; this.y = y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
}
C:\src\java\generics>javac Line.java
C:\src\java\generics>java Line
(1,1) ... (2,2)
Wow, you look HOT! ... What's your sign?
C:\src\java\generics>