/** * A better Toilet. It automatically cleans up after itself if it * overflows, so it never throws an exception. It also tries to raise * and lower the seat for you, although this turned out to be a bad idea. * * @author Jason Eisner * @version 1.0, 2003-01-26 */ public class AutoToilet extends Toilet { /** Like {@link Toilet#flush}, but cleans up instead of throwing an exception. */ public void flush() { try { super.flush(); } catch (FloatingOverflowException e) { System.out.println("Caught exception, cleaning up mess."); System.out.print("Retrying flush: "); this.flush(); } } /** Although we inherit the general {@link Toilet#deposit(Waste)} method * from our parent class, we also override it with this more specific * method for liquid waste. The method automatically raises and lowers * the seat for you when you pee. Alas, tests show dissatisfaction * among female users. * @param lw The liquid waste */ public void deposit(LiquidWaste lw) { raiseSeatAuto(true); deposit((Waste) lw); // call the general method; alternatively, super.deposit(lw) raiseSeatAuto(false); } /** Since this kind of toilet has an automatic seat raiser, the user * can't move the seat. So we override the inherited raiseSeat * method with one that has no effect. (We do print a warning message; * alternatively, we could throw an exception.)

* * Really we shouldn't even be able to call raiseSeat * at all on an {@link AutoToilet}. Unfortunately, by defining a * raiseSeat method for {@link Toilet}, we have told * the compiler that it's legal to call raiseSeat on * any {@link Toilet} object, including subclasses. So we'd have * to change that -- i.e., only some subclasses of {@link Toilet} should * support this method. */ public void raiseSeat(boolean b) { // overrides general method. System.out.println("Thanks for trying to adjust the seat, but it's not necessary for this fancy toilet."); } /** Internally, the class's implementation will call this * protected method to move the seat. The user can't call * this. */ protected void raiseSeatAuto(boolean b) { System.out.print("Whirr ... creak ... "); // sound of the motor super.raiseSeat(b); // call superclass method, as if user had moved seat } /** Test function similar to {@link Toilet#main}. */ public static void main(String args[]) { // doesn't throw anything AutoToilet throne = new AutoToilet(); throne.raiseSeat(true); // unnecessary now throne.deposit(new LiquidWaste("pee")); // auto raises/lowers seat (new LiquidWaste("more pee")).deposit(throne); // auto raises/lowers seat throne.deposit(new SolidWaste("poo")); // no auto-flush in this version throne.deposit(new SolidWaste("more poo")); throne.flush(); throne.deposit(new TrashWaste("cigarettes")); throne.flush(); // auto-cleans if overflow System.out.println("All done. No need to destroy toilet; it will be garbage-collected."); } }