/* File Succ.java Part of Natural Number Example H. Conrad Cunningham, Professor 1234567890123456789012345678901234567890123456789012345678901234567890 2004-01-17: Original 2016-10-26: Formatting changes, compilation check Class Succ represents the successor function in the natural number definition. It maps its argument (i.e., contained Nat value) to its successor (i.e., one larger value). It is a composite subclass in the Composite pattern. */ public class Succ extends Nat { public Succ(Nat n) { val = n; } public Nat pred() // operation of Succ, not Nat { return val; } public Nat add(Nat n) { return val.add(new Succ(n)); } // m + n = (m-1)+(n+1) public Nat sub(Nat n) { if (n == Zero.getZero()) { return this; } // m - 0 = m return val.sub(((Succ)n).pred()); // m - n = (m-1) - (n-1) } public boolean isLess(Nat n) { if (n == Zero.getZero()) { return false; } // m > 0S return val.isLess(((Succ)n).pred()); // m < n = (m-1)<(n-1) } // Normally we should avoid use of instanceof in OO code, but // it is often necessary in comparisons. public boolean equals(Object n) // method from class Object { if (!(n instanceof Succ)) { return false; } return val.equals(((Succ)n).pred()); // (m=n) = ((m-1)=(n-1)) } public String toString() // method from class Object { return ("1+" + val); } private Nat val; // predecessor value }