ITEC120-ibarland—info—lectures—labs
Oct.11 (Wed.): For this lab, work individually. Check off your work before you leave lab, or at the start of lab on Friday.
Back in an early lab, we wrote a couple of methods for computing tax. The method priceAfterTax added sales tax to an item, which often is the correct thing to do, but not always: Some times (food) are tax-free. Some times there are tax-free shopping days for back-to-school supplies. There might be other obscure situations where tax doesn't need to be added (internet purchases which are shipped out-of-state, perhaps).
So: We want to improve our original priceAfterTax function so that it takes a second input, in addition to the purchase price: it will accept a boolean value isTaxable, and will compute the final price (which may or may not include tax, depending on whether the caller passed in true or false).
TaxMan.priceAfterTax(100, false) == 100 // A non-taxable $100 item. TaxMan.priceAfterTax(100, true) == 105 // A taxable $100 item. TaxMan.priceAfterTax(100, (100 > 25)) == 105 /* If we had a method todayIsATaxFreeDay(), you could imagine * that clothing and school supplies might call something like * TaxMan.priceAfterTax(100, todayIsATaxFreeDay() ); */ TaxMan.priceAfterTax(100) == 105 // We didn't break our old code. |
Interestingly, it's no problem having two versions of priceAfterTax in the same class. Even though they have the same name, when somebody calls one of them, Java can distinguish which one of the two functions is intended by looking at the two signatures (do they pass a double, or a double-and-a-boolean?).
It is called overloading a method, when you have two different versions which both have the same name. You must be able to distinguish them just by the input types; Java doesn't use the return type (partly because it does so much auto-converting of things to Strings behind-the-scene).
Overloading is convenient, but it isn't a deep concept:
if Java didn't happen to provide it for us, we could still get the same
effect just by giving
slightly different names to each function
(“salesTax_isTaxable”,
“salesTax_isTaxable_taxrate”, etc.).
After all, when somebody is writing code which calls
one version or the other, they know at that moment
which arguments they want to pass in,
so they'd know which version to call even if they had different names.
Overloading just lets us avoid having
to think up and remember several similar names.
Today we will check off TaxMan if you haven't already, and discuss and work on writing last week's PairODice well.
Specific things to look for:1Provided the company has an office in that other state; otherwise sales tax isn't required there. back
ITEC120-ibarland—info—lectures—labs
©2006, Ian Barland, Radford University Last modified 2006.Oct.13 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |