COP 3530 Section U02 Fall 2012 A Generic Point Program ======================= I. The class Point.java // example of a generic class public class Point { // the fields private T xCoord; private T yCoord; // the constructor public Point(T x, T y) { xCoord = x; yCoord = y; } // the set methods public void setX(T x) { xCoord = x; } public void setY(T y) { xCoord = y; } // the get methods public T getX() { return xCoord; } public T getY() { return yCoord; } } II. A driver // a driver for the Point class public class Generics1 { public static void main(String[] args) { // print the title System.out.println("Testing the Generic Point Class"); System.out.println("===============================\n\n"); // form a point with real coordinates System.out.println("We form a point with coordinates 3.5 and 2.3 . "); Point p1 = new Point(3.5,2.3); printPoint(p1); // form a point with String coordinates System.out.println("\nWe form a point with coordinates \"Poco\" and \"Pelo\" ."); Point p2 = new Point("Poco", "Pelo"); printPoint(p2); System.out.println("We change the x-coordinate to \"Muy Poco\" ."); p2.setX("Muy Poco"); System.out.println("The x-coordinate is " + p2.getX()); // form a point with integer coordinates but set T= Double System.out.println("\nWe form a point with coordinates 3 and 2. "); Integer a = new Integer(3); Integer b = new Integer(2); Point p3 = new Point<>(a,b); int x = p3.getX(); System.out.println("The x-coordinate is " + x); // form a point with real coordinates but set T= Integer System.out.println("We form a point with coordinates 3.5 and 2.3 . "); Point p4 = new Point<>(3.5,2.3); // syntax error printPoint(p4); } // the printPoint method public static void printPoint(Point point) { System.out.println("The x-coordinate is " + point.getX()); System.out.println("The y-coordinate is " + point.getY()); } } III. The output: run: Testing the Generic Point Class =============================== We form a point with coordinates 3.5 and 2.3 . The x-coordinate is 3.5 The y-coordinate is 2.3 We form a point with coordinates "Poco" and "Pelo" . The x-coordinate is Poco The y-coordinate is Pelo We change the x-coordinate to "Muy Poco" . The x-coordinate is Muy Poco Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - The type of Point(T,T) is erroneous at generics1.Generics1.main(Generics1.java:42) We form a point with coordinates 3 and 2. The x-coordinate is 3 We form a point with coordinates 3.5 and 2.3 . Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)