Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lecture Writing Classes

Similar documents
Lecture Overview. Knowledge-based systems in Bioinformatics, 1MB602. Procedural abstraction. The sum procedure. Integration as a procedure

box Boxes and Arrows 3 true 7.59 'X' An object is drawn as a box that contains its data members, for example:

Data sharing in OpenMP

Reference types and their characteristics Class Definition Constructors and Object Creation Special objects: Strings and Arrays

CS201 Discussion 10 DRAWTREE + TRIES

cisc1110 fall 2010 lecture VI.2 call by value function parameters another call by value example:

How to Design REST API? Written Date : March 23, 2015

Agenda & Reading. Class Exercise. COMPSCI 105 SS 2012 Principles of Computer Science. Arrays

Functor (1A) Young Won Lim 10/5/17

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lecture A very small selection of some topics in Object-Oriented Design

MIPS I/O and Interrupt

ECE 468/573 Midterm 1 September 28, 2012

Pointers and Arrays. More Pointer Examples. Pointers CS 217

Virtual Machine (Part I)

From Dependencies to Evaluation Strategies

In the last lecture, we discussed how valid tokens may be specified by regular expressions.

Functor (1A) Young Won Lim 8/2/17

Introduction To Files In Pascal

Unit 5 Vocabulary. A function is a special relationship where each input has a single output.

Very sad code. Abstraction, List, & Cons. CS61A Lecture 7. Happier Code. Goals. Constructors. Constructors 6/29/2011. Selectors.

vcloud Director Service Provider Admin Portal Guide vcloud Director 9.1

Distributed Systems Principles and Paradigms

CIS 1068 Program Design and Abstraction Spring2015 Midterm Exam 1. Name SOLUTION

- 2 U NIX FILES 1. Explin different file types vilble in UNIX or P OSIX s ystem. ( 08 mrks) ( My-08/Dec-08/My-10/My- 12) 2. Wht is n API? How is it di

CPSC 213. Polymorphism. Introduction to Computer Systems. Readings for Next Two Lectures. Back to Procedure Calls

pdfapilot Server 2 Manual

Discussion 1 Recap. COP4600 Discussion 2 OS concepts, System call, and Assignment 1. Questions. Questions. Outline. Outline 10/24/2010

Outline. Tiling, formally. Expression tile as rule. Statement tiles as rules. Function calls. CS 412 Introduction to Compilers

Math 464 Fall 2012 Notes on Marginal and Conditional Densities October 18, 2012

Memory Management Functions

Mid-term exam. Scores. Fall term 2012 KAIST EE209 Programming Structures for EE. Thursday Oct 25, Student's name: Student ID:

CSCE 531, Spring 2017, Midterm Exam Answer Key

10.5 Graphing Quadratic Functions

MA1008. Calculus and Linear Algebra for Engineers. Course Notes for Section B. Stephen Wills. Department of Mathematics. University College Cork

Dynamic Programming. Andreas Klappenecker. [partially based on slides by Prof. Welch] Monday, September 24, 2012

Creating Flexible Interfaces. Friday, 24 April 2015

Geometric transformations

Systems I. Logic Design I. Topics Digital logic Logic gates Simple combinational logic circuits

CS321 Languages and Compiler Design I. Winter 2012 Lecture 5

Fall 2018 Midterm 1 October 11, ˆ You may not ask questions about the exam except for language clarifications.

Midterm 2 Sample solution

COMPUTER SCIENCE 123. Foundations of Computer Science. 6. Tuples

Deposit a Technical Report in PubRep

Virtual Machine I: Stack Arithmetic

1 Quad-Edge Construction Operators

vcloud Director Service Provider Admin Portal Guide 04 OCT 2018 vcloud Director 9.5

4452 Mathematical Modeling Lecture 4: Lagrange Multipliers

UNIT 11. Query Optimization

L2-Python-Data-Structures

TO REGULAR EXPRESSIONS

Sample Midterm Solutions COMS W4115 Programming Languages and Translators Monday, October 12, 2009

10/9/2012. Operator is an operation performed over data at runtime. Arithmetic, Logical, Comparison, Assignment, Etc. Operators have precedence

ASTs, Regex, Parsing, and Pretty Printing

Preserving Constraints for Aggregation Relationship Type Update in XML Document

Definition of Regular Expression

Reducing Costs with Duck Typing. Structural

Reducing a DFA to a Minimal DFA

If f(x, y) is a surface that lies above r(t), we can think about the area between the surface and the curve.

Fig.25: the Role of LEX

Some Thoughts on Grad School. Undergraduate Compilers Review and Intro to MJC. Structure of a Typical Compiler. Lexing and Parsing

COMMON HALF YEARLY EXAMINATION DECEMBER 2018

A Formalism for Functionality Preserving System Level Transformations

Spring 2018 Midterm Exam 1 March 1, You may not use any books, notes, or electronic devices during this exam.

Topic: Software Model Checking via Counter-Example Guided Abstraction Refinement. Having a BLAST with SLAM. Combining Strengths. SLAM Overview SLAM

CS412/413. Introduction to Compilers Tim Teitelbaum. Lecture 4: Lexical Analyzers 28 Jan 08

Tool Vendor Perspectives SysML Thus Far

Readings : Computer Networking. Outline. The Next Internet: More of the Same? Required: Relevant earlier meeting:

Dr. D.M. Akbar Hussain

EECS 281: Homework #4 Due: Thursday, October 7, 2004

Unit #9 : Definite Integral Properties, Fundamental Theorem of Calculus

CSEP 573 Artificial Intelligence Winter 2016

Container Vs. Definition Classes. Container Class

COMP 423 lecture 11 Jan. 28, 2008

Coprocessor memory definition. Loic Pallardy / Arnaud Pouliquen

VoIP for the Small Business

CS 340, Fall 2014 Dec 11 th /13 th Final Exam Note: in all questions, the special symbol ɛ (epsilon) is used to indicate the empty string.

Digital Design. Chapter 6: Optimizations and Tradeoffs

Engineer-to-Engineer Note

Assignment 4. Due 09/18/17

Fall 2018 Midterm 2 November 15, 2018

Scanner Termination. Multi Character Lookahead. to its physical end. Most parsers require an end of file token. Lex and Jlex automatically create an

! Smaller, simpler, subcomponent of program! Provides abstraction. n hide low-level details, give high-level structure

Stained Glass Design. Teaching Goals:

vcloud Director Tenant Portal Guide vcloud Director 9.1

VoIP for the Small Business

Presentation Martin Randers

OPERATION MANUAL. DIGIFORCE 9307 PROFINET Integration into TIA Portal

VoIP for the Small Business

5 Regular 4-Sided Composition

Small Business Networking

Improper Integrals. October 4, 2017

Slides for Data Mining by I. H. Witten and E. Frank

Scope, Functions, and Storage Management

VoIP for the Small Business

Today. Search Problems. Uninformed Search Methods. Depth-First Search Breadth-First Search Uniform-Cost Search

Fig.1. Let a source of monochromatic light be incident on a slit of finite width a, as shown in Fig. 1.

VoIP for the Small Business

50 AMC LECTURES Lecture 2 Analytic Geometry Distance and Lines. can be calculated by the following formula:

520 Principles of Programming Languages. Memory Management. Memory Management... 35: Garbage Collection

CSc 453. Compilers and Systems Software. 4 : Lexical Analysis II. Department of Computer Science University of Arizona

Transcription:

Introduction to Computer Science, Shimon Schocken, IDC Herzliy Lecture 5.1-5.2 Writing Clsses Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 1 Clsses Two viewpos on es: Client view: how to use n existing Server view: how to design, implement, nd min es Two min uses of es: Auxiliry es: Mth, Definition es: String, Turtle,, Where Jv es come from: The Jv stndrd librry Clsses tht or people write nd mke vilble Clsses tht I write. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 2

Outline Modulrity Abstrction Clss ntomy Fields Constructors Methods Relted topics Method overloding Revisiting Prmeter pssing Vrible life cycle Encpsultion Method ntomy Clss vs. instnce methods Types nd vlues Methods prmeters Accessors nd muttors Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 3 Modulrity When building complex rtifct, it lwys helps to divide chllenge o smll, mngeble modules Ech module must hve Clerly defined function Contrct s to how it ercts with or modules Self-contined design tht enbles unit-testing nd locl mennce In prticulr, when we write, we hve to think how to divide things tht is supposed to do o methods Exmple: let s look t two versions of squreroot from Exercise 3 Un-modulr version Modulr version. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 4

Un-modulr version import import jv.util.scnner; SqureRoot SqureRoot finl finl EPSILON EPSILON 0.1; 0.1; min(string rgs[]) rgs[]) Scnner Scnner scn scn Scnner(System.in); Get Get user's user's input input System.out.pr("Enter number: number: "); "); x scn.nextint(); Problems with unmodulr code The I/O processing nd sqrt computtion re glued toger It s hrd to tell which prt of progrm is responsible for run-time bugs If we ll wnt to chnge I/O only, we hve to chnge entire The sqrt services re inccessible to or clients The design is not elegnt Solution: divide nd conquer. Compute Compute squre squre root root flot flot root root x / 2; 2; while while (Mth.bs((root root) root) - x) x) > EPSILON) EPSILON) improve improve guess guess root root (root (root (x (x/ root)) root)) / 2; 2; Pr Pr result result System.out.prln( The squre squre root root is: is: " sqrt(x)); sqrt(x)); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 5 Modulr version import import jv.util.scnner; SqureRootDemo min(string rgs[]) rgs[]) I/O Scnner Scnner scn scn Scnner(System.in); Get Get number number from from user user nd nd squre squre it it System.out.pr("Enter number: number: "); "); x scn.nextint(); System.out.prln( The squre squre root root is: is: " sqrt(x)); sqrt(x)); Wht hve we gined? Redbility Elegnce Unit testing Code re-use Prllel development Computes Computes squre squre root root function function processing sqrt( x) x) precision precision 0.1; 0.1; root root x / 2; 2; while while (Mth.bs((root root) root) - x) x) > precision) precision) root root (root (root (x (x/ root)) root)) / 2; 2; root; root; Using methods is just one exmple of modulr design Modulrity is key design objective tht comes up in numerous res in CS Modulr design begins t bstrction level. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 6

Outline Modulrity Abstrction Clss ntomy Fields Constructors Methods Relted topics Method overloding Revisiting Prmeter pssing Vrible life cycle Encpsultion Method ntomy Clss vs. instnce methods Types nd vlues Methods prmeters Accessors nd muttors Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 7 Abstrction OO progrm design begins with bstrctions Abstrctions re used to describe objects like cr, bnk ccount, turtle, friend, etc. To describe n object bstrction, we think bout it terms of: Wht re its ttributes? ( dt-oriented view) Wht re its behviors? ( functionl view) Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 8

Exmple: bstrction A is n object tht keeps nd reports time using 24- hour system Attributes: Hours Minutes Seconds Behviors: Crete clock Advnce clock 1 second Query clock time Etc. implementtion (structure only) The The clock clock stte stte (dt) (dt) hours, hours, constructor ( ( h, h, m, m, s); s); Advnce Advnce clock clock one one second second forwrd forwrd secondelpsed(); Query Query methods methods gethours(); getminutes(); getseconds(); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 9 Using (exmple) server The The clock clock stte stte hours, hours, constructor constructor ( ( h, h, m, m, s); s); Advnce Advnce clock clock one one second second forwrd forwrd secondelpsed(); secondelpsed(); client Using (n exmple) Some Some Query Query methods methods gethours(); gethours(); Crete Crete nd nd initilize initilize clock clock object object getminutes(); getminutes(); nytime nytime (23,59,59); (23,59,59); getseconds(); getseconds(); Advnce Advnce clock clock 50 50 seconds seconds for for ( ( j j j j < < 5 5 j) j) nytime.secondelpsed(); nytime.secondelpsed(); Pr Pr clock s clock s current current time time System.out.pr( The System.out.pr( The time time in in New New York York is: is: ); ); System.out.prln(nyTime.getHours() System.out.prln(nyTime.getHours() nytime.gethours() nytime.gethours() : : nytime.getminutes() nytime.getminutes() : : nytime.getseconds()); nytime.getseconds()); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 10

Outline Modulrity Abstrction Clss ntomy Fields Constructors Methods Relted topics Method overloding Revisiting Prmeter pssing Vrible life cycle Encpsultion Method ntomy Clss vs. instnce methods Types nd vlues Methods prmeters Accessors nd muttors Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 11 Clss members structure Clss members Fields Constructors The The clock clock stte stte hours, hours, constructor ( ( h, h, m, m, s); s); Advnce Advnce clock clock one one second second forwrd forwrd secondelpsed(); Methods Query Query methods methods gethours(); getminutes(); getseconds(); Visibility modifiers: Privte members: visible only to code; typiclly used for fields Public members: visible to code of or es; typiclly used for methods. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 12

Fields The object's stte (dt) is represented by vribles, AKA instnce vribles or fields Fields re vribles: y cn be of eir primitive or types Ech object hs nd seprte set of fields The fields re typiclly initilized by constructors. structure The The clock clock stte stte hours, hours, constructor ( ( h, h, m, m, s); s); Advnce Advnce clock clock one one second second forwrd forwrd secondelpsed(); Query Query methods methods gethours(); getminutes(); getseconds(); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 13 Constructor server When creting object, we normlly wish to specify its initil stte The The clock clock stte stte This is done using hours, hours, constructor: specil method which is Cretes Cretes object object nd nd initilizes invoked by commnd its its fields fields using using supplied supplied vlues vlues c ( ); ( ( h, h, m, m, s) s) hours hours h; h; minutes minutes m; m; client seconds seconds s; s; Public Public SomeClss SomeClss Or Or methods methods follow follow c1; c1; c1 c1 (12,0,0); c2 c2 (10,60,45); This client code cuses server code to crete two objects. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 14

The this keyword The The clock clock stte stte hours, hours, Constructor: one one style style ( ( h, h, m, m, s) s) hours hours h; h; minutes minutes m; m; seconds seconds s; s; Inside n instnce method, this keyword refers to object on which method is currently operting this cn be thought of s generic object vrible, poing to current object. Constructor: Constructor: nor nor style style ( ( hours, hours,,, seconds) seconds) ) this.hours hours hours hours; hours; this.minutes minutes minutes; minutes; this.seconds seconds seconds Constructor Or Or methods methods follow follow Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 15 Constructor definition, properly documented using Jvdoc hours, hours, / / Cretes Cretes clock clock nd nd set set it it to to specified specified time. time. If If one one of of prmeters prmeters is is not not in in llowed llowed rnge, rnge, constructor constructor hs hs no no effect effect on on clock s clock s stte. stte. @prm @prm hours hours The The hours hours to to be be set set (0-23) (0-23) @prm @prm minutes minutes The The minutes minutes to to be be set set (0-59) (0-59) @prm @prm seconds seconds The The seconds seconds to to be be set set (0-59) (0-59) / / Resulting API, following jvdoc.jv ( ( hours, hours, seconds) seconds) if if ((seconds ((seconds > > 0) 0) && && (seconds (seconds < < 60) 60) && && (minutes (minutes > > 0) 0) && && (minutes (minutes < < 60) 60) && && (hours (hours > > 0) 0) && && (hours (hours < < 24)) 24)) this.hours this.hours hours; hours; this.minutes this.minutes minutes; minutes; this.seconds this.seconds Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 16

Constructor ntomy, behind scene Creting Cloc object (exmple) SomeClss SomeClss c1, c1, c2, c2, c3; c3; c1 c1 (13,0,0); c2 c2 (22,10,1); When n object vrible is declred, only reference vrible is llocted The object dt is creted if nd when constructor is invoked vi... 10102 Memory... 75101 10103 98607 c2 10104... 75101 75102 75103... 98607... 98612...... 13 0 0... 22 10 1... c1 c3 c1 object c2 object Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 17 Outline Modulrity Abstrction Clss ntomy Fields Constructors Methods Relted topics Method overloding Revisiting Prmeter pssing Vrible life cycle Encpsultion Method ntomy Clss vs. instnce methods Types nd vlues Methods prmeters Accessors nd muttors Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 18

Methods A method, k subroutine, is stnd-lone piece of code designed to crry out well defined computtion or opertion Clss () methods: ssocited with level. Exmple: sqrt Instnce methods: methods tht re ssocited with objects. Exmple: turnright method ssocited with prticulr Turtle objects Clss methods provide generl-purpose functionlity Instnce methods implement object behviors. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 19 Instnce method exmple server hours, hours, Constructor (omitted) (omitted) The desired behviors of object re implemented by methods. Ech method is designed to perform one bstrct opertion Advnce Advnce clock clock by by 1 second second client secondelpsed() Public if if (seconds (seconds < 59) Public someclss someclss 59) else else c (12,0,0); seconds seconds c.secondelpsed(); if if (minutes (minutes < 59) 59) minutes minutes ; else else minutes minutes hours hours hours hours < 24 24? Hours Hours 1 : 1; 1; Semntics: invoke secondelpsed method on c (or methods) ( object tht c refers to). methods) Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 20

Method types nd vlues client SomeClss SomeClss server c (0,0,0); hours, hours, Invoking Invoking method method c.hourelpsed(2); hourelpsed() Invoking Invoking typed typed methods methods hours hours (hours (hours 1) 1) % 24; 24; h c.gethours(); System.out.prln(c.toString); gethours() gethours() hours; hours; String String tostring() tostring() (hours (hours "\t" "\t" minutes minutes "\t" "\t" seconds); seconds); Void method: hs no type nd no vlue Typed method: hs eir primitive type or n object type. Returns vlue tht must conform to method s type. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 21 Method prmeters Methods my or my not hve prmeters A prmeter is like locl vrible which is initilized by method s cller. Forml prmeters cllee settime( hours, hours, seconds) seconds) if if ((seconds ((seconds > > 0) 0) && &&(seconds < 60) 60) && && (minutes (minutes > > 0) 0) && &&(minutes < 60) 60) && && (hours (hours > > 0) 0) && &&(hours < 24)) 24)) this.hours this.hours hours; hours; cller this.minutes minutes; minutes; Public this.seconds Public someclss someclss c1 c1 (12, (12, 0, 0, 0); 0); no no effect effect if if input input is is invlid invlid c1.settime(2, 15, 15, 0); 0); Actul prmeters (rguments) Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 22

By wy Current Current time time represented by by clock clock hours, hours, Now tht we hve settime method, it mkes sense to re-define constructor. Constructor ( ( hours, hours, seconds) seconds) settime(hours, seconds); seconds); Sets Sets time time to to given given vlues vlues settime( hours, hours, seconds) seconds) if if ((seconds ((seconds > > 0) 0) && &&(seconds < 60) 60) && && (minutes (minutes > > 0) 0) && &&(minutes < 60) 60) && && (hours (hours > > 0) 0) && &&(hours < 24)) 24)) this.hours this.hours hours; hours; this.minutes minutes; minutes; this.seconds no no effect effect if if input input is is invlid invlid Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 23 Accessor methods server hours, hours, Accessor methods: used to query nd informtion bout vribles Enble controlled ccess to vribles from outside. gethours() gethours() hours; hours; getminutes() minutes; minutes; getseconds() client someclss someclss c (12,0,0); h c.gethours(); System.out.pr(c.getSeconds) Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 24

Muttor methods server hours, hours, sethours( hours) hours) if if ((h ((h > 0) 0) && &&(h (h < < 24)) 24)) this.hours this.hours hours; hours; setminutes( minutes) minutes) if if ((m ((m > > 0) 0) && &&(m (m < 60)) 60)) this.minutes minutes; minutes; setseconds( seconds) seconds) if if ((s ((s > > 0) 0) && &&(s (s < 60)) 60)) this.seconds Muttor methods: used to set vlues of vribles Enble controlled updte of vribles from outside. client someclss someclss dedlinehour 2 2 c (12,0,0); c.sethours(17); c.sethours(dedlinehour-1); c.setminutes(scn.nextint()); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 25 Method invoction exmples Demo Demo min(string[] rgs) rgs) c1 c1 (12,59,59); c2 c2 (12,59,59); h gethours(); h c1.gethours()); 12 12 c1.secondelpsed(); Error! Which clock re we tlking bout? Invoking method System.out.prln(c1.getHours()); 1 System.out.prln(c2.getHours()); 12 12 x Mth.sqrt(c2.getMinutes()); Sttic method invoction Instnce method invoction Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 26

Outline Modulrity Abstrction Clss ntomy Fields Constructors Methods Relted topics Method overloding Revisiting Prmeter pssing Vrible life cycle Encpsultion Method ntomy Clss vs. instnce methods Types nd vlues Methods prmeters Accessors nd muttors Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 27 Method overloding cllee MyMth MyMth sum sum ( ( x, x, y)) y)) x x y; y; sum sum ( ( x, x, y, y, z)) z)) x x y y z; z; sum sum ( ( x, x, y)) y)) x x y; y; cller SomeClss SomeClss System.Out.prln(MyMth.sum(5,3)); System.Out.prln(MyMth.sum(5,3)); Will Will prs prs 8 8 System.Out.prln(MyMth.sum(7,2,8)); System.Out.prln(MyMth.sum(7,2,8)); Will Will prs prs 17 17 System.Out.prln(MyMth.sum(5.3,4)); System.Out.prln(MyMth.sum(5.3,4)); Will Will pr pr 9.3 9.3 Jv llows defining different methods with sme nme Method signture: method nme, prmeter types, prmeter nmes Jv knows which method to invoke ccording to method signture implied by cller Advntges: Promotes shorter, fewer, nd redble method nmes. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 28

Method overloding SqureRootDemo min(string rgs[]) rgs[]) System.out.prln(sqrt(17) sqrt(17)); System.out.prln(sqrt(17, sqrt(17, sqrt(17, 0.0001)); 0.0001)); sqrt( sqrt( x) x) sqrt(x,0.1); sqrt( sqrt( x, x, precision) precision) root root x / 2; 2; while while (Mth.bs((root root) root) - x) x) > precision) precision) root root (root (root (x (x/ root)) root)) / 2; 2; root; root; Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 29 Constructor overloding hours, hours, server Constructors Constructors ( ( hours, hours, seconds) seconds) settime(hours, settime(hours, seconds); seconds); client ( ( hours) hours) someclss someclss this.hours this.hours hours; hours; this.minutes this.minutes c1 c1 (12,59,59); this.seconds this.seconds c2 c2 (12); c3 c3 (); (); Alterntive Alterntive definition: definition: ( ( hours) hours) this(hours, this(hours, 0 0,0);,0); () () hours hours minutes minutes seconds seconds An overloded constructor provides multiple wys to set up object. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 30

revisited Account Account numbers numbers re re llocted llocted from from 1 1 onwrd. onwrd. nextaccountnumber nextaccountnumber 1; 1; Fields Fields number; number; Account Account number number String String owner; owner; Account Account owner owner blnce; blnce; Current Current blnce blnce Sets Sets up up ccount ccount (String (String owner, owner, blnce) blnce) this.number this.number nextaccountnumber; nextaccountnumber; this.owner this.owner owner; owner; this.blnce this.blnce blnce; blnce; Returns Returns textul textul object object description description String String tostring tostring () () (number (number "\t" "\t" owner owner "\t" "\t" () () blnce); blnce); Demo Demo server (Only subset of members is shown) client min(string[] min(string[] rgs) rgs) liceaccount liceaccount ("Alice", ("Alice", 0); 0); bobaccount bobaccount ("Bob", ("Bob", 100); 100); System.out.prln(liceAccount.toString()); System.out.prln(liceAccount.toString()); System.out.prln(bobAccount.toString()); System.out.prln(bobAccount.toString()); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 31 revisited Only Only subset subset of of members members is is shown shown server bnkdeposits bnkdeposits client Demo Demo Fields Fields number; number; min(string[] min(string[] rgs) rgs) String String owner; owner; liceaccount liceaccount ("Alice", ("Alice", 0); 0); blnce; blnce; bobaccount ("Bob", 100); bobaccount ("Bob", 100); System.out.prln(liceAccount.toString()); Hndles Hndles deposit System.out.prln(liceAccount.toString()); deposit deposit deposit ( ( mount) mount) System.out.prln(bobAccount.toString()); System.out.prln(bobAccount.toString()); chrge chrge commission(mount); commission(mount); blnce blnce blnce blnce mount mount - - chrge; liceaccount.deposit(1000); chrge; liceaccount.deposit(1000); bnkdeposits bnkdeposits (mount (mount chrge); chrge); liceaccount.trnsferto(300,bobaccount); liceaccount.trnsferto(300,bobaccount); System.out.prln(liceAccount.toString()); System.out.prln(liceAccount.toString()); System.out.prln(bobAccount.toString()); Hndles Hndles withdrwl System.out.prln(bobAccount.toString()); withdrwl withdrw withdrw ( ( mount) mount) chrge chrge commission(mount); commission(mount); blnce blnce blnce blnce - - mount mount - - chrge; chrge; bnkdeposits bnkdeposits - - (mount (mount - - chrge) chrge) ; ; Hndles Hndles trnsfer trnsfer Constructor trnsferto( trnsferto( mount, mount, trgetaccount) trgetaccount) trgetaccount.deposit(mount); trgetaccount.deposit(mount); this.withdrw(mount); this.withdrw(mount); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 32

revisited Only Only subset subset of of members members is is shown shown bnkdeposits bnkdeposits finl finl COMMISSION_RATE COMMISSION_RATE 0.005; 0.005; finl finl COMMISSION_STEP COMMISSION_STEP 500 500 number; number; String String owner; owner; blnce; blnce; Hndles Hndles deposit deposit deposit deposit ( ( mount) mount) chrge chrge commission(mount); commission(mount); blnce blnce blnce blnce mount mount - - chrge; chrge; bnkdeposits bnkdeposits (mount (mount chrge); chrge); Returns Returns blnce blnce getblnce getblnce () () blnce; blnce; Returns Returns commission commission tht tht bnk bnk chrges chrges for for mount mount commission commission ( Constructor ( mount) mount) ((mount ((mount > > COMMISSION_STEP) COMMISSION_STEP)?? (mount (mount COMMISSION_RATE COMMISSION_RATE / / 2) 2) : : (mount (mount COMMISSION_RATE)); COMMISSION_RATE)); Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 33 Cll by vlue / cll by reference cllee Fields Fields number; number; String String owner; owner; blnce; blnce; Hndles Hndles trnsfer trnsfer Cll by vlue Cll by reference trnsferto( trnsferto( mount, mount, trgetaccount) trgetaccount) trgetaccount.deposit(mount); trgetaccount.deposit(mount); this.withdrw(mount); this.withdrw(mount); mount mount 100000 100000 just just for for demo demo cller liceacc liceacc ( Alice, ( Alice, 800); 800); bobacc bobacc ( Bob, ( Bob, 100); 100); Cll by vlue: Used when prmeter is of primitive type A vlue is computed nd pssed to method The method cnnot chnge prmeter. mount mount 500 500 liceacc.trnsfer(mount, liceacc.trnsfer(mount, bobacc); bobacc); System.out.prln(mount); System.out.prln(mount); Will Will pr pr 500. 500. Cll by reference Used when prmeter is of object type A poer to object is pssed to method The method cn chnge referred object. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 34

Vrible life cycle Sttic vribles Instnce vribles Locl vribles Sttic vribles: creted first time method from is invoked Instnce vribles: creted when object is creted nd recycled when object is destroyed Locl vribles: creted when method is invoked nd recycled when it s Prmeters: sme s locl vribles. Initilized by rguments supplied by cller. lstaccountnumber 1; 1; bnkdeposits number; number; String String owner; owner; blnce; blnce; Sets Sets up up ccount ccount (String (String owner, owner, blnce) blnce) this.number lstaccountnumber; this.owner this.owner owner; owner; this.blnce blnce; blnce; prmeter Hndles Hndles withdrwl withdrwl withdrw withdrw ( ( mount) mount) blncetemp blnce blnce mount mount if if (blncetemp > > 0) 0) blnce blnce blncetemp; bnkdeposits - - mount; mount; else else omitted omitted Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 35 Outline Modulrity Abstrction Clss ntomy Fields Constructors Methods Relted topics Method overloding Revisiting Prmeter pssing Vrible life cycle Encpsultion Method ntomy Clss vs. instnce methods Types nd vlues Methods prmeters Accessors nd muttors Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 36

Encpsultion bstrction: A is n object tht keeps nd reports time using 24- hour system Required services: Crete clock Advnce clock 1 second Query clock time Set clock time ( (hours, seconds) secondelpsed() getseconds() getminutes() gethours() Encpsultion: Seprting contrctul erfce of n bstrction from its implementtion. setseconds() setminutes() sethours() More More services Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 37 Encpsultion Clients Methods deposit() withdrw() Dt tildown number x,y Owner direction blnce trnsfer() getblnce() Encpsultion: Etc Hiding, or encpsulting, ernl stte of object from outside Protects egrity of object by preventing users from setting its ernl dt o n invlid or inconsistent stte A criticlly importnt OO design objective. Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 38

Encpsultion nd visibility modifiers Vribles Violte encpsultion Enforce encpsultion Methods Provide services to clients Support or methods in sme Writing Clsses, Shimon Schocken IDC Herzliy, www.ro2cs.com slide 39