CS110 Lecture 16 Tuesday, March 30, 2004 • Announcements – hw7 due Thursday – pass/fail, withdraw deadline April 8 • Agenda – – – – – – Questions toString Bank (5) switch, flow control Trees JFile system Lecture 16 1 toString • Suppose SomeClass foo = new SomeClass( ) • Then these two expressions do the same thing: System.out.println( foo.toString() ); System.out.println( foo ); • Every object knows how to respond to a toString message since there’s a toString in class Object • For “foo” etymology, see the full online dictionary of computer science at http://foldoc.doc.ic.ac.uk Lecture 16 2 class OverridingDemo • It’s often nice to override toString, to provide an informative String describing your particular kind of object • NamedObject overrides toString (71-74) • Create NamedObject instances named by command line arguments (33, 40) • println … 34 nobj.toString() 35 nobj itself 36 toString from class Object Lecture 16 implicit toString message weird 3 toString in class Object • NamedObject@206fdf64 • Not very informative • (class name)@(weird number) • weird number is actually base 16 (hexadecimal) (digits 0123456789abcde) • weird number may change when program runs again Lecture 16 4 toString in class Boolean • Wrapper class for primitive type boolean • From file Boolean.java in library: private boolean value; // field public String toString() { return value ? "true" : "false"; } • Sun’s brace convention differs from ours • test ? x : y expression on next slide Lecture 16 5 test ? x : y • Has value x if test is true, else has value y if (a > b) { max = a; } else { max = b; } same as max = ( a > b ) ? a : b; Lecture 16 6 toString for collections • TreeMapDemo.java 108 terminal.println(map.toString()); produces output {one=1, three=3, two=1} “{ (key.toString()=value.toString(), … }” • ArrayList toString produces “[ 0th item toString, 1st item toString … ]” • Very useful for debugging Lecture 16 7 Bank(version 5) • How does program decide which kind of account to open? • How simulated time works • Polymorphism • Code in hw7/bank/Bank.java also answers hw6 Lecture 16 8 switch (Bank.java 116) String accountName = atm.readWord ("Account name: " ); char accountType = atm.readChar ("Check/Fee/Reg/Sav? (c/f/r/s): " ); int start = atm.readInt("Initial deposit: " ); BankAccount newAccount; switch( accountType ) { case 'c': newAccount = new CA( bal, this ); break; case 'f': newAccount = new FA( bal, this ); break; default: atm.println ("invalid account type: " + accountType); return; } Lecture 16 9 switch • Easier to read than if - else if - else if … . • Variable whose value you switch on must be int or char (or long or short) • Remember the break statement, lest you fall through to next case (a common error) • Java design flaw – should use { … block …} • new keywords: default, case, switch, break see JOI/examples/SwitchDemo.java Lecture 16 10 Closing an account while (!(transaction = atm.readWord (" transaction: ")).equals("quit")) { . . . else if (transaction.equals("close")) { close(acct); // private in Bank break; } } • Require whole word “close” to close account, use “cash check” or “check” to cash check Lecture 16 11 Leaving a loop body prematurely while or for ( … ) { … redo loop from top (do test) if ( … ) continue; if ( … ) leave loop break; if ( … ) return from method return; … last in loop; } next statement; • Sometimes makes for easy reading, avoids many else statements. • Sometimes confusing - can’t trace flow without reading loop body. Lecture 16 see JOI/examples/BreakandContinueDemo.java 12 newMonth Bank.java (203) private void newMonth() { month.next(); for (BankAccount acct: accountList) { acct.newMonth(); } } • • No cast: every subclass of BankAccount must implement the abstract newMonth method Real code is Java 1.4 (this is Java 1.5) Lecture 16 13 Polymorphism poly (many) + morph (shape) • Bank – maintains a list of BankAccount objects – sends them messages – without knowing what kinds of BankAccounts they are! • Client refers to objects of type Parent that are really instances of a Child extending Parent • Each child responds in its own particular way • Powerful design tool - ignorance is bliss Lecture 16 14 Polymorphism atm.println(" withdrew " + acct.withdraw( amount )); • • • • • Checking and Regular accounts just do it FeeAccount charges a fee SavingsAccount keeps track of transactions in this month No casting, since BankAccount has a withdraw method Polymorphism is in countTransaction, invoked by withdraw Lecture 16 15 Here we need a cast 146 process…ForAccount( BankAccount acct ) 165 else if ( trans.startsWith("ca" ) || 166 trans.startsWith("ch" ) ) { 167 int amount = atm.readInt ( " amount of check: " ); 168 atm.println(" cashed check for " 169 ((CA)acct).honorCheck(amount )); 170 } • Note use of || (or). Use && for and. • “c” is ambiguous since we can close account Lecture 16 16 Trees • Common in computer science: – Java class hierarchy (shows inheritance) – Windows tree for files and directories (folders) • • • • Vocabulary: Tree, hierarchy Root (often drawn at the top!) Child, parent, branch, leaf, node Draw with arrows, or in outline form Lecture 16 17 Class hierarchy Note descriptive words root Lecture 16 18 File system organization • folder: place where Windows keeps information • For historical reasons, we use “directory” as a synonym for “folder” • A directory can contain – other directories (called subdirectories, subfolders) – files • Every directory is a subdirectory of its parent • In Windows, each drive (C:, A:) has a root directory, called “\”, with no parent • Each directory is the root for the tree of things inside it Lecture 16 19 root files are leaves Tree for cs110 web page Lecture 16 20 Design problem • Directory can store TextFiles and Directories • Directory and TextFile both have – owner, create/mod date (same meaning) – size, contents (different meanings) • Directory has methods to add to, get from and loop on its contents (the TreeMap of files in it) • TextFile has methods to manipulate its text • Can we write these classes without copying code? Lecture 16 21 class Object Inheritance class JFile - fields and methods needed by all child classes (deal with owner and Dates), abstract getSize method class TextFile - fields and methods just for TextFile (String contents, append …) class Directory - fields and methods just for Directory (TreeMap jfiles, add and retrieve JFiles, ...) Lecture 16 22 JFile system uses two trees Java class hierarchy Directory and TextFile hierarchy class Object root eb hello insult cs110 diary bill class JFile class Directory class TextFile Lecture 16 23 JFile (easy part) • private fields for String name String owner Date createDate Date modDate • getters and setters as appropriate • abstract getSize method since each child must provide its own implementation: – number of JFiles in a Directory – number of characters in a TextFile • main for unit testing – 1/4 of the source code – tedious but straightforward – read it now Lecture 16 24 Testing JFile, Directory, TextFile • JFile has static code for testing – public static main – private static methods out, list, type – private static field for Terminal (visible in all static methods) • main builds a tree of JFiles – documented on lines 210-217 – constructed on lines 218-229 – explored on lines 231-251 Lecture 16 25 Look at list • list is passed a Directory to list – we might have put list in class Directory and asked a Directory to list itself. We didn’t, because Directory knows nothing about printing. Client sends a getContents message instead, and does its own printing • The idiom test ? yes : no • loop on contents (like unit test in hw4) • line 238: jfile.getSuffix • Send a message to a JFile object without knowing whether it’s a TextFile or a Directory Lecture 16 26 Polymorphism poly (many) + morph (shape) • Directory.java – maintains a list of JFile objects – client retrieves them and sends them messages – without knowing what kinds of JFiles they are! • Client refers to objects of type Parent that are really instances of a Child extending Parent • Powerful design tool - ignorance is bliss Lecture 16 27 JFile getSuffix • ls -f on mars appends “/” for directory listing (e.g. hw5 in cs110) “@” for symbolic link (e.g. cs110 in your home) “*” for an executable file (e.g. mkdir in /bin) (on Unix many commands are really files) no suffix for ordinary text files, class files, ... • We want JFiles to behave this way • Ask a JFile to tell you its suffix by sending it a getSuffix message • getSuffix is abstract in JFile.java Lecture 16 28 “\” vs “/” • Windows uses one, Unix the other • Java knows about both • File.java (in the Java API) declares public static final String separator • JFile.java declares public static String separator = File.separator Lecture 16 29 Managing the JFile tree • A Directory – keeps a TreeMap of JFiles (the Directory’s jfile field) keyed by name – has methods to add and retrieve JFiles by name – has a method that allows client to loop on contents • A JFile has a parent field in which it keeps a reference to the Directory it belongs to (like BankAccount – Bank) Lecture 16 30 JFile constructor • JFile.java, line 50 protected: visible to children, not public • lines 52-53 are easy: they initialize fields if (parent != null) (line 54) parent.addJFile( name, this ); • if this JFile has a parent (not top of JFile tree) send message to parent to add this JFile (Directory or TextFile) to its TreeMap, with name as key. (Directory.java line 69) • Careful: parent directory != parent class Lecture 16 31 Constructors in a subclass • Client creates a Directory with a name, an owner and in a particular directory (like mkdir): JFile.java line 236: Directory cs110 = new Directory(“cs110”, “eb”, home1); • Directory.java constructor – line 34: initialize TreeMap declared on 21 (familiar from Chapter 4, hw4) – line 33: invoke parent class (JFile) constructor (java keyword super is “my parent”) Lecture 16 32