SWE/CS 332 In Class Exercise # 6
September 18, 2017


Name(s):

public class Poly {

    private int[] trms;
    private int deg;

    // Effects: Initializes this to be the zero polynomial
    public Poly() {
       trms = new int[1]; trms[0] = 0;
       deg = 0;
    }

    // Effects: If n < 0 throws IllegalArgumentException
    // else initializes this to be the polynomial c*x^n
    public Poly(int c, int n) throws IllegalArgumentException {
       if (n < 0) {
          throw new IllegalArgumentException("Poly(int, int) constructor");
       }
       if (c == 0) {
          trms = new int[1]; trms[0] = 0;
          deg = 0;
          return;
       }
       trms = new int[n+1];
       for (int i=0; i < n; i++) {
          trms[i] = 0;
       }
       trms[n] = c;
       deg = n;
    }

    private Poly (int n) {
       trms = new int[n+1];
       deg = n;
    }

// Effects: If q is null throw NullPointerException // else return the Poly this + q public Poly add(Poly q) throws NullPointerException { Poly la, sm; if (deg > q.deg) { la = this; sm = q; } else { la = q; sm = this; } int newdeg = la.deg; if (deg == q.deg) { for (int k = deg; k > 0; k--) { if (trms[k] + q.trms[k] != 0) { break; } else { newdeg--; } } } Poly r = new Poly(newdeg); int i; for (i = 0; i <= sm.deg && i <= newdeg; i++) { r.trms[i] = sm.trms[i] + la.trms[i]; } for (int j = i; j <= newdeg; j++) { r.trms[j] = la.trms[j]; } return r; } }

Liskov classifies methods into four kinds. What are they, and which ones are represented here?

What happens to methods of these types when converting between mutable and immutable implementations?

Convert the fragment of Liskov's Poly class into a mutable data type. What's tricky about this?