Exercise Sheet 3 Interfaces Exercise 1 (a) Write an interface Printable which has a single method put whose intention is to display a string representation of any object whose class implements Printable. Check it by compiling it. (b) Enhance classes Point and Time from Chapter 2 of the notes to implement Printable. Check them by compiling them. (c) Write a static method print which takes an array of objects whose class implements Printable, and prints each element in the array, one element per line. Check it by placing it in an otherwise empty class and compiling it. (d) Program OrderDemo in Chapter 2 of the notes has more or less duplicate code that prints in one place an array of Point objects, and in another an array of Time objects. Remove the duplication by using method print described above. (The duplicated code is admittedly short, but it could in principle be much longer). (e) Include in your program of Part (d) a further test for print as follows. Create a small array mixed which contains both Point and Time objects and use method print to print out mixed. Exercise 2 (a) Copy classes Triangle and Point from Chapter 1 of the lecture notes, and interface Order from Chapter 2. Amend Triangle to implement Order. In the context of triangles, method lte in Order compares triangles based on their area, i.e. a triangle is less than or equal to another if its area is less than or equal to the area of the other triangle. Note that class Point is not changed and class Triangle has code added but no existing code changed or removed. (b) Test your re-written class using the program given below which creates and reads in an array of triangles and prints them in sorted order (by area). It is convenient to re-direct the standard input, which is done by placing the following (say) vertices of three triangles in a text file called, say, tri3.txt and running the program as java OrderTest < tri3.txt. 4.1 4.6 6.1 2.8 4.5 6.7 1.2 3.1 CA213 Exercises 3 1 3.4 5.3 7.3 5.3 7.2 5.4 8.6 9.3 8.1 9.8 class OrderTest { static void sort(Order[] w) { // Sort w[0..] final int n = w.length; int j = 0; // w[j..] to be sorted while (j<n-1) { int min = j; int i = j+1; while (i<n) { if (w[i].lte(w[min])) min = i; i++; } Order temp= w[j]; w[j] = w[min]; w[min] = temp; j++; } } public static void main(String[] args) { Triangle[] ts = new Triangle[3]; System.out.println( "Enter " + ts.length + " triangles:"); for (int i=0; i<ts.length; i++) { ts[i] = new Triangle(); ts[i].get(); } sort(ts); for (Triangle t: ts) System.out.println(t); } } CA213 Exercises 3 2