/* --- CSU213 Fall 2006 Lecture Notes --------- Copyright 2006 Viera K. Proulx Lecture 4: September 13, 2006 Designing Methods for Simple Classes */ /* +--------------+ | TStop | +--------------+ | String name | | String line | | int price | +--------------+ */ // to represent a subway station class TStop { String name; String line; int price; // in cents TStop(String name, String line, int price) { this.name = name; this.line = line; this.price = price; } /* TEMPLATE: ... this.name ... -- String ... this.line ... -- String ... this.price ... -- int */ // to determine whether one token is enough at this stop boolean oneToken(){ return this.price == 125; } // is this station on the given line? boolean myLine(String line){ return this.line.equals(line); } // is this stop on the same line as the given stop? boolean sameLine(TStop that){ /* TEMPLATE: ... this.name ... -- String ... this.line ... -- String ... this.price ... -- int ... that.name ... -- String ... that.line ... -- String ... that.price ... -- int */ return this.line.equals(that.line); } // increase the price of fare at this station by the given amount TStop increasePrice(int amount) { return new TStop(this.name, this.line, this.price + amount); } // produce the cheaper station between this one and the given one TStop cheaperStop(TStop that){ if (this.price <= that.price) return this; else return that; } } class ExamplesIStation{ ExamplesIStation() {} /* Harvard station on the Red line costs \$1.25 to enter Kenmore station on the Green line costs \$1.25 to enter Riverside station on the Green line costs \$2.50 to enter */ TStop harvard = new TStop("Harvard", "red", 125); TStop kenmore = new TStop("Kenmore", "green", 125); TStop riverside = new TStop("Riverside", "green", 250); // tests for the method oneToken in the class TStop boolean testOneToken = (check this.harvard.oneToken() expect true) && (check this.kenmore.oneToken() expect true) && (check this.riverside.oneToken() expect false); // tests for the method myLine in the class TStop boolean testMyLine = (check this.harvard.myLine("red") expect true) && (check this.riverside.myLine("red") expect false); // tests for the method sameLine in the class TStop boolean testSameLine = (check this.harvard.sameLine(this.kenmore) expect false) && (check this.riverside.sameLine(this.kenmore) expect true); // tests for the method increasePrice in the class TStop boolean testIncreasePrice = (check this.harvard.increasePrice(20) expect new TStop("Harvard", "red", 145)) && (check this.riverside.increasePrice(50) expect new TStop("Riverside", "green", 300)); // tests for the method cheaperStop in the class TStop boolean testCheaperStop = (check this.harvard.cheaperStop(this.kenmore) expect this.harvard) && (check this.riverside.cheaperStop(this.harvard) expect this.harvard) && (check this.kenmore.cheaperStop(this.riverside) expect this.kenmore); }