class Posn { int x; int y; Posn(int x, int y) { this.x = x; this.y = y; } } // ---------------------------------------- abstract class Animal { // feeds this n lbs abstract Animal feed(double n); } class Snake extends Animal { String name; double weight; String food; Snake(String name, double weight, String food) { this.name = name; this.weight = weight; this.food = food; } // determines whether it's < n lbs boolean isLighter(double n) { return n > this.weight; } boolean isBiggerThanAnt(Ant a) { return this.weight > a.weight; } // feed this n lbs // Note: the result type was originally // Snake, but we had to change it to Animal // so that all Animals could have the same // feed method Animal feed(double n) { return new Snake(this.name, this.weight + n, this.food); } } // Test: // new Snake("Slinky", 10, "rats").feed(3) // "should be" new Snake("Slinky", 13, "rats") class Dillo extends Animal { double weight; boolean alive; Dillo(double weight, boolean alive) { this.weight = weight; this.alive = alive; } // feeds this n lbs Animal feed(double n) { return new Dillo(this.weight + n, this.alive); } } // Test: // new Dillo(5, true).feed(2) "should be" new Dillo(7, true) class Ant extends Animal { double weight; Posn loc; Ant(double weight, Posn loc) { this.weight = weight; this.loc = loc; } // feeds this n lbs Animal feed(double n) { return new Ant(this.weight + n, this.loc); } } // Test: // new Ant(0.0001, new Posn(0, 0)).feed(0.0002) // "should be" new Ant(0.0003, new Posn(0, 0)) // Old Scheme data-defn for list-of-num: // ; A list-of-num // ; - empty // ; - (cons num list-of-num) // Translateable Scheme data-defn for list-of-num: // ; A list-of-num // ; - empty-list // ; - cons-list // ; An empty-list is // ; (make-empty-list) // (define-struct empty-list ()) // ; A cons-list is // ; (make-cons-list num list-of-num) // (define-struct cons-list (first rest)) abstract class NumList { abstract int length(); } class EmptyNumList extends NumList { EmptyNumList() { } int length() { return 0; } } class ConsNumList extends NumList { int first; NumList rest; ConsNumList(int first, NumList rest) { this.first = first; this.rest = rest; } int length() { return 1 + this.rest.length(); } }