class BoundedWildcardDemo
1: //BoundedWildcardDemo.java.
2: //Demonstrate a bounded wildcard.
4: class BoundedWildcardDemo
5: {
6: //A method to display the first two co-ordinates.
7: //Can use a wildcard parameter since any element of the input
8: //co-ordinate array is guaranteed to have at least the first
9: //two co-ordinates.
10: static void showXY(Coords<?> c)
11: {
12: System.out.println("X Y Coordinates:");
13: for (int i = 0; i < c.coords.length; i++)
14: {
15: System.out.println(c.coords[i].x + " " + c.coords[i].y);
16: }
17: System.out.println();
18: }
20: //Prevents any TwoD objects in Coords
21: static void showXYZ(Coords<? extends ThreeD> c)
22: {
23: System.out.println("X Y Z Coordinates:");
24: for (int i = 0; i < c.coords.length; i++)
25: {
26: System.out.println
27: (
28: c.coords[i].x + " "
29: + c.coords[i].y + " "
30: + c.coords[i].z
31: );
32: }
33: System.out.println();
34: }
36: static void showAll(Coords<? extends FourD> c)
37: {
38: System.out.println("X Y Z T Coordinates:");
39: for (int i = 0; i < c.coords.length; i++)
40: {
41: System.out.println
42: (
43: c.coords[i].x + " "
44: + c.coords[i].y + " "
45: + c.coords[i].z + " "
46: + c.coords[i].t
47: );
48: }
49: System.out.println();
50: }
52: public static void main(String args[])
53: {
54: TwoD twoD[] =
55: {
56: new TwoD(0, 0),
57: new TwoD(7, 9),
58: new TwoD(18, 4),
59: new TwoD(-1, -23)
60: };
62: Coords<TwoD> twoDlocations = new Coords<TwoD>(twoD);
64: System.out.println("Contents of twoDlocations.");
65: showXY(twoDlocations); //OK, twoDlocations is a TwoD
66: //showXYZ(twoDlocations); //Error, twoDlocations is not a ThreeD
67: //showAll(twoDlocations); //Erorr, twoDlocations is not a FourD
69: //Now, create some FourD objects.
70: FourD fourD[] =
71: {
72: new FourD(1, 2, 3, 4),
73: new FourD(6, 8, 14, 8),
74: new FourD(22, 9, 4, 9),
75: new FourD(3, -2, -23, 17)
76: };
78: Coords<FourD> fourDlocations = new Coords<FourD>(fourD);
80: System.out.println("Contents of fourDlocations.");
81: //These are all OK ...
82: showXY(fourDlocations);
83: showXYZ(fourDlocations);
84: showAll(fourDlocations);
85: }
86: }