Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 161 CS110 Lecture 16 Tuesday, March 30, 2004 Announcements –hw7 due Thursday –pass/fail, withdraw deadline April 8 Agenda –Questions –toString.

Similar presentations


Presentation on theme: "Lecture 161 CS110 Lecture 16 Tuesday, March 30, 2004 Announcements –hw7 due Thursday –pass/fail, withdraw deadline April 8 Agenda –Questions –toString."— Presentation transcript:

1 Lecture 161 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 Lecture 162 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 Lecture 163 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 Lecture 164 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 Lecture 165 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 Lecture 166 test ? x : y Has value x if test is true, else has value y same as if (a > b) { max = a; } else { max = b; } max = ( a > b ) ? a : b;

7 Lecture 167 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 “[ 0 th item toString, 1 st item toString … ]” Very useful for debugging

8 Lecture 168 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 Lecture 169 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 Lecture 1610 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

11 Lecture 1611 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 Lecture 1612 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. return from method redo loop from top (do test) leave loop see JOI/examples/BreakandContinueDemo.java

13 Lecture 1613 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 Lecture 1614 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 Lecture 1615 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 Lecture 1616 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 Lecture 1617 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 Lecture 1618 Class hierarchy Note descriptive words root

19 Lecture 1619 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 Lecture 1620 Tree for cs110 web page files are leaves root

21 Lecture 1621 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 Lecture 1622 Inheritance class Directory - fields and methods just for Directory (TreeMap jfiles, add and retrieve JFiles,...) class TextFile - fields and methods just for TextFile (String contents, append …) class JFile - fields and methods needed by all child classes (deal with owner and Dates), abstract getSize method class Object

23 Lecture 1623 JFile system uses two trees Java class hierarchy class Object class JFile class Directoryclass TextFile Directory and TextFile hierarchy root eb bill hello cs110 diary insult

24 Lecture 1624 JFile (easy part) private fields for String name Date createDate String ownerDate 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 Lecture 1625 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 Lecture 1626 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 Lecture 1627 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 Lecture 1628 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 Lecture 1629 “\” 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 Lecture 1630 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 Lecture 1631 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 Lecture 1632 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”)


Download ppt "Lecture 161 CS110 Lecture 16 Tuesday, March 30, 2004 Announcements –hw7 due Thursday –pass/fail, withdraw deadline April 8 Agenda –Questions –toString."

Similar presentations


Ads by Google