/* Date: Mon, 14 Feb 2005 18:21:07 +0000 (UTC) From: John B. Clements Newsgroups: ccs.courses.csu213 Subject: Lecture code 2005-02-10 (monkeymangler.java) */ // mangles a monkey interface MonkeyMangler { boolean mangle(int weight); } // A Mangler for monkeys under 100 lbs. class UnderOneHundred implements MonkeyMangler { UnderOneHundred(){} boolean mangle(int weight){ return (weight < 100); } } // A Mangler for monkeys over 200 lbs. class OverTwoHundred implements MonkeyMangler { OverTwoHundred(){} boolean mangle(int weight){ return (weight > 200); } } // lists of animals abstract class LoA { // is 'this' object extensionally equivalent to 'other'? abstract boolean same(Object other); // mangles a list of monkeys abstract LoA mangleMonkeys(MonkeyMangler mm); } // represent a list of animals class MT extends LoA { MT() { } boolean same(Object other) { if (other instanceof MT) return true; else return false; } LoA mangleMonkeys(MonkeyMangler mm){ return new MT(); } } class Cons extends LoA { Monkey first; LoA rest; Cons(Monkey first, LoA rest) { this.first = first; this.rest = rest; } boolean same(Object other) { if (other instanceof Cons) return (this.first.same(((Cons)other).first)) && (this.rest.same(((Cons)other).rest)) && true; else return false; } LoA mangleMonkeys(MonkeyMangler mm){ if (mm.mangle(this.first.weight)) return new Cons(this.first,this.rest.mangleMonkeys(mm)); else return this.rest.mangleMonkeys(mm); } } // represent animals abstract class Animal { // is 'this' object extensionally equivalent to 'other'? abstract boolean same(Object other); } // represent monkeys class Monkey extends Animal { int weight; Monkey(int weight) { this.weight = weight; } boolean same(Object other) { if (other instanceof Monkey) return (this.weight == ((Monkey)other).weight) && true; else return false; } } // represent Elephants class Elephant extends Animal { int numOfLegs; Elephant(int numOfLegs) { this.numOfLegs = numOfLegs; } boolean same(Object other) { if (other instanceof Elephant) return (this.numOfLegs == ((Elephant)other).numOfLegs) && true; else return false; } } // represent a Hippopotamus class Hippo extends Animal { int numOfHeads; Hippo(int numOfHeads) { this.numOfHeads = numOfHeads; } boolean same(Object other) { if (other instanceof Hippo) return (this.numOfHeads == ((Hippo)other).numOfHeads) && true; else return false; } } class Examples{ Examples(){} Monkey m1 = new Monkey(25); LoA l1 = new Cons(this.m1,new Cons(new Monkey(400),new MT())); //boolean s1 = (this.l1.onlyLittleMonkeys().same(new Cons(this.m1,new MT()))); //boolean s2 = (this.l1.onlyBigMonkeys().same(new Cons(new Monkey(400),new MT()))); boolean s3 = (this.l1.mangleMonkeys(new UnderOneHundred()).same(new Cons(this.m1,new MT()))); }