

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


1
2
3
4
5
6
7
8
public class Debt implements Measurable { private double balance, payment, intRate;
public Debt (double bal, double pay, double rate) { //etc. }
public boolean greaterThan (Measurable rhs) { Debt x = (Debt) rhs; // type cast return balance > x.balance; }
public double getMeasure() { return balance; }
// toString, etc. }
Required by the Measurable interface
9
public class Shape implements Measurable { private String shapeName;
public Shape() { shapeName = ”undefined”; } // etc.
public boolean greaterThan (Measurable rhs) { Shape x = (Shape) rhs; // type cast return area() > x.area(); // dynamic binding
public double getMeasure() { return area(); } }
Required by the Measurable interface
10
public class GenericList { private Measurable[] myData; private int count; public GenericList(int size) { count = 0; myData = new Measureable[size]; }
public void addSorted(Measurable d) { int k = 0; while ((k < count) && d.greaterThan(myData[k])) k++; for (int j = count; j > k; j--) myData[j] = myData[j-1]; myData[k] = d; count++; } // etc. }
Dynamic binding
Type is interface name
Array of Measurable references, not Measurable instantiation
11
// other declarations ... GenericList debtList = new GenericList(10); GenericList shapeList = new GenericList(10);
debtList.addSorted(new Debt(5000.00, 327.51, 0.055)); debtList.addSorted(new Debt(2000.00, 200.00, 0.06)); // etc. ...
shapeList.addSorted(new Circle(3.0)); shapeList.addSorted(new Square(7.1)); // etc. ...
12
debtList.addSorted(new Circle(3.0));
while ((k < count) && d.greaterThan(myData[k]))
public boolean greaterThan (Measurable rhs) { Shape x = (Shape) rhs; // type cast