/*********************************************** * CS2510 Fall 2011 * Lecture #4.2 * Data and Methods (instance functions) ***********************************************/ import tester.*; interface ITrain { // Length returns the length of the train int length(); // Biggest returns the number of passengers of the largest car int biggest(); // MaxWeight returns the largest weight of the cars in the train double maxWeight(); } class Lead implements ITrain { int hp; ITrain next; /* Fields of *this*: * ... this.hp -- int * ... this.next -- ITrain * * Methods of *this*: * ... this.length() ... -- int * ... this.biggest() ... -- int * ... this.maxWeight() ... -- double */ Lead(int hp, ITrain next) { this.hp = hp; this.next = next; } // Returns 1 plus the length of the rest of the train public int length() { return this.next.length() + 1; } // Returns the biggest of the rest, as this car holds no // passengers public int biggest() { return next.biggest(); } // A lead car weighs 1lb / 10 hp public double maxWeight() { return Math.max(2000 + hp/10, next.maxWeight()); } } class Cab implements ITrain { int passengerc; ITrain next; /* Fields of *this*: * ... passengerc -- int * ... next -- ITrain * * Methods of *this*: * ... this.length() ... -- int * ... this.biggest() ... -- int * ... this.maxWeight() ... -- double */ Cab(int passengerc, ITrain next) { this.passengerc = passengerc; this.next = next; } // Returns 1 + length of the rest of the train public int length() { return this.next.length() + 1; } // Returns the larger of this car and the rest of the cars public int biggest() { return Math.max(passengerc, next.biggest()); } public double maxWeight() { return Math.max(2000 + passengerc*150,next.maxWeight()); } } class Kaboose implements ITrain { /* Fields of *this*: * ... * * Methods of *this*: * ... this.length() ... -- int * ... this.biggest() ... -- int * ... this.maxWeight() ... -- double */ Kaboose(){ } // Length returns 1 as there are no cars after it public int length() { return 1; } // Biggest returns 0 as there are no passengers // and no cars after it public int biggest() { return 0; } public double maxWeight() { return 2000; } } class TrainExamples { // Examples of Train types Kaboose k = new Kaboose(); Cab c1 = new Cab(20,new Cab(50,new Cab(15,k))); Lead leadcar = new Lead(2500,c1); Kaboose k2 = new Kaboose(); Lead leadcar2 = new Lead(1000,k2); int trainlength = leadcar.length(); boolean testLength(Tester t) { return t.checkExpect(leadcar.length(),5) && t.checkExpect(leadcar2.length(),2); } boolean testBiggest(Tester t) { return t.checkExpect(leadcar.biggest(),50) && t.checkExpect(leadcar2.biggest(),0); } boolean testMaxWeight(Tester t) { return t.checkExpect(leadcar.maxWeight(),2000.0+(50*150)) && t.checkExpect(leadcar2.maxWeight(),2100.0); } }