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

Slides:



Advertisements
Similar presentations
Written by: Dr. JJ Shepherd
Advertisements

CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
Lecture 181 CS110 Lecture 18 Tuesday, April 6, 2004 Announcements –hw8 due Thursday, April 8 –pass/fail, withdraw deadline Thursday, April 8 Agenda –Questions.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Lecture 171 CS110 Lecture 17 Thursday, April 1, 2004 Announcements –hw7 due tonight –pass/fail, withdraw deadline April 8 Agenda –Questions –Juno –JFile.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Writing Classes (Chapter 4)
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
Lecture 61 CS110 Lecture 6 Thursday, February 12, 2004 Announcements –hw2 due today Agenda –questions –testing –modeling text files –declarations (classes,
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Java Programming Language
Lecture 21 CS110 Lecture 2 January 29, 2004 Announcements –hw1 part 1 – due right now –hw1 part 2 – due Tuesday night Questions Agenda –turnin –Object.
1 21 COP 3540 Data Structures with OOP Overview: Chapter 1.
Lecture 131 CS110 Lecture 13 Thursday, March 11, 2004 Announcements –hw5 due tonight –Spring break next week –hw6 due two weeks from tonight Agenda –questions.
Lecture 71 CS110 Lecture 7 February 17, 2004 Announcements –hw3 due Thursday Agenda –questions –hw3 tips –getters and setters – information hiding –delegation.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Introduction to Java Java Translation Program Structure
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
M1G Introduction to Programming 2 5. Completing the program.
Lecture 71 CS110 Lecture 8 February 19, 2004 Announcements –hw3 due tonight –hw4 available, due Thursday February 26 –exam Tuesday March 2 Agenda –questions.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Wednesday –POD –I have updated grades in powerschool. If you have a zero for a lab grade, it probably means you didn’t DropItToMe. Please do so. –Slides.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
OOP Basics Classes & Methods (c) IDMS/SQL News
Object-Oriented Programming: Polymorphism Chapter 10.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
CS110 Introduction to Programming Lecture 1 January 27, 2004 Ethan Bolker Philosophy Bank: user interface, Java, object model Programming environment Homework.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 5:Interfaces and Abstract Classes
3 Introduction to Classes and Objects.
Programming Language Concepts (CIS 635)
Object Oriented Programming (OOP) LAB # 8
Chapter 4: Writing classes
Anatomy of a Method.
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Review of Previous Lesson
Chap 2. Identifiers, Keywords, and Types
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
References Revisted (Ch 5)
Classes and Methods 15-Aug-19.
Presentation transcript:

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

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

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

Lecture 164 toString in class Object Not very informative (class number) weird number is actually base 16 (hexadecimal) (digits abcde ) weird number may change when program runs again

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

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;

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

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

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; }

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

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

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

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)

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

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

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

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

Lecture 1618 Class hierarchy Note descriptive words root

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

Lecture 1620 Tree for cs110 web page files are leaves root

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?

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

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

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

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 –constructed on lines –explored on lines

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

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

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

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

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)

Lecture 1631 JFile constructor JFile.java, line 50 protected : visible to children, not public lines 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 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”)