Notes
Slide Show
Outline
1
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
2
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
3
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      implicit toString message
    • 36 toString from class Object    weird
4
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
5
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
6
test ? x : y
  • Has value x if test is true, else has value y





  • same as
7
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
8
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
9
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;
  • }
10
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
11
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


12
Leaving a loop body prematurely

    • while or for (   …   ) {
    •    …
    •    if ( … )
    •       continue;
    •    if ( … )
    •       break;
    •    if ( … )
    •       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.
13
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)


14
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


15
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
16
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
17
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


18
Class hierarchy
19
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



20
Tree for cs110 web page
21
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?
22
Inheritance
23
JFile system uses two trees
24
JFile (easy part)
  • private fields for
    • String name Date createDate
    • String owner 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
25
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

26
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
27
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



28
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
29
“\” 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
30
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)
31
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
32
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”)