Cs110 lecture 16 tuesday march 30 2004
Download
1 / 32

CS110 Lecture 16 Tuesday, March 30, 2004 - PowerPoint PPT Presentation


  • 118 Views
  • Uploaded on

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. toString. Suppose SomeClass foo = new SomeClass( )

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' CS110 Lecture 16 Tuesday, March 30, 2004' - agatha


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Cs110 lecture 16 tuesday march 30 2004
CS110 Lecture 16Tuesday, 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


Tostring
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


Class overridingdemo
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

Lecture 16


Tostring in class object
toString in class Object

  • [email protected]

  • 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


Tostring in class boolean
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’sbrace convention differs from ours

  • test ? x : y expression on next slide

Lecture 16


Test x y
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;

Lecture 16


Tostring for collections
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


Bank version 5
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


Switch bank java 116
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


Switch
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


Closing an account
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


Leaving a loop body prematurely
Leaving a loop body prematurely

redo loop from top (do test)

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.

leave loop

return from method

Lecture 16

see JOI/examples/BreakandContinueDemo.java


Newmonth bank java 203
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


Polymorphism poly many morph shape
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


Polymorphism
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


Here we need a cast
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


Trees
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


Class hierarchy
Class hierarchy

Note descriptive words

root

Lecture 16


File system organization
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 aroot directory, called “\”, with no parent

  • Each directory is the root for the tree of things inside it

Lecture 16


Tree for cs110 web page
Tree for cs110 web page

root

files are leaves

Lecture 16


Design problem
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


Inheritance
Inheritance

class Object

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


Jfile system uses two trees
JFile system uses two trees

Java class hierarchy

Directory and TextFile hierarchy

class Object

root

eb

hello

class JFile

insult

cs110

diary

bill

class Directory

class TextFile

Lecture 16


Jfile easy part
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

Lecture 16


Testing jfile directory textfile
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


Look at list
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


Polymorphism poly many morph shape1
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


Jfile getsuffix
JFile getSuffix

  • ls -f on mars appends

    “/” for directory listing (e.g. hw5 in cs110)

    [email protected] 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


“\” 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


Managing the jfile tree
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


Jfile constructor
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


Constructors in a subclass
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


ad