/* File Err.java Part of Natural Number Example H. Conrad Cunningham, Professor 1234567890123456789012345678901234567890123456789012345678901234567890 2004-01-17: Original 2016-10-26: Formatting changes, compilation check Class Err represents an error condition. It is a leaf subclass in the Composite pattern and is designed and implemented with the Singleton pattern to ensure that exactly one instance is created. Perhaps in a more sophisticated version, Err would carry an indicator of what type of error is needed. In that case, a Singleton could not be used. */ public class Err extends Nat { private Err () { } // private constructor for Singleton public Nat add(Nat n) { return this; } // Err + n = Err public Nat sub(Nat n) { return this; } // Err - n = Err public boolean isLess(Nat n) { return false; } // Not comparable. Probably bad design. // equals is tricky because of Err nesting down inside Succ // structures. (As noted elsewhere, it is normally best not to // use instanceof calls in OO code, but it is often necessary in // comparisons.) public boolean equals(Object n) { if (n == this) { return true; } // Err = Err if (n == Zero.getZero()) { return false; } // Err != 0 if (!(n instanceof Nat)) { return false; } return (equals(((Succ)n).pred())); // Err = Succ(Err) } public String toString() // method from class Object { return "ERR"; } // Set up a Singleton for this type public static Err getErr() { return theErr; } private static Err theErr = new Err(); }