/*********************************** * CS2510 Spring 2011 * Lecture #4.2 * Unions, Recursion, and *IF* ***********************************/ import tester.*; // Represents a Train interface ITrain{ // Calculate the length of this Train int length(); // Calculate the maximum weight of a Car // in this train int maxWeight(); } // Represents a Kabuse class Kabuse implements ITrain{ Kabuse(){} /* Template * Methods * ... this.length() ... -- int * ... this.maxWeight() ... -- int */ // Calculate the length of this Kabuse int length(){ return 1; } // Calculate the maximum weight of this Kabuse int maxWeight(){ return 0; } } // Respresents a Train Car class Car implements ITrain{ int weight; ITrain next; Car(int weight, ITrain next){ this.weight = weight; this.next = next; } /* Template * Fields * ... this.weight ... -- int * ... this.next ... ITrain * * Methods * ... this.length() ... -- int * ... this.maxWeight() ... -- int * * Methods of Fields * ... this.next.length() ... -- int * ... this.next.maxWeight() ... -- int * */ // Calculate the length of this Car int length(){ return 1+this.next.length(); } // Which one is the Maximum? int max(int a, int b){ if(a > b){ return a; }else{ return b; } } // Calculate the maximum weight of this Car int maxWeight(){ return this.max(this.weight, this.next.maxWeight()); } } // Examples and Tests for Trains class TrainExamples{ TrainExamples(){} ITrain t1 = new Kabuse(); ITrain t2 = new Car(1, t1); // To Test the length method boolean testLength(Tester t){ return (t.checkExpect(this.t1.length(), 1) && t.checkExpect(this.t2.length(), 2)); } // To Test the maxWeight method boolean testMaxWeight(Tester t){ return (t.checkExpect(this.t1.maxWeight(), 0) && t.checkExpect(this.t2.maxWeight(), 1)); } }