Скачать презентацию Chapter 3 Object Oriented Design and Writing Worker Скачать презентацию Chapter 3 Object Oriented Design and Writing Worker

50dc546a729952eb39fa35ac391897d7.ppt

  • Количество слайдов: 76

Chapter 3 Object Oriented Design and Writing Worker Classes Chapter 3 Object Oriented Design and Writing Worker Classes

Structure of classes We will begin to write 2 classes for each project – Structure of classes We will begin to write 2 classes for each project – Worker or Support class – Application or client class The intent is to create classes that are reusable Reuse is an important aspect of OOP

Section 3. 1 First Worker Class We will carefully study a class that represents Section 3. 1 First Worker Class We will carefully study a class that represents Food Items in a grocery store. Worker classes are meant to represent real world objects. They model a real world entity. Keep this in mind as we analyze this class.

Review of class definitions 1. 2. A Header declaration The class body a. The Review of class definitions 1. 2. A Header declaration The class body a. The data field declarations of the class b. The method definitions of the class

Class Data fields The data fields of a class are also called instance variables. Class Data fields The data fields of a class are also called instance variables. These are chosen very carefully! Only the data that represents the object is part of the class data fields. Do not put all necessary variables here. Other variables will be used in you methods later.

Class Data Field The values in these fields represent the “state” of the object. Class Data Field The values in these fields represent the “state” of the object. The Food. Item fields are: public class Food. Item { // data fields private String description; private double size; private double price;

Class Data Fields Class data fields always have visibility of private. This means they Class Data Fields Class data fields always have visibility of private. This means they can be accessed from anywhere in the class, but can not be accessed from outside the class. This is a form of encapsulation that we will discuss further later.

Class Data Fields Because we make our class data fields private they can only Class Data Fields Because we make our class data fields private they can only be accessed via the class methods. Syntax Diagram: [visibility] type. Name datafield. Name = [value];

Visibility 4 types of visibility exist: – private (only class) – public (anywhere) – Visibility 4 types of visibility exist: – private (only class) – public (anywhere) – protected (class and subclasses) – default (package (in same folder))

Initial values You can optionally include initial values for your data fields. private double Initial values You can optionally include initial values for your data fields. private double price = 1. 0; Later we will learn to use this in very powerful ways.

Method Definitions Form: method header { method body } The header gives the method Method Definitions Form: method header { method body } The header gives the method name and parameters and return value which are both optional.

Syntax Diagram visibility [static] result. Type method. Name([parameter. List]) public static void main(string[] args) Syntax Diagram visibility [static] result. Type method. Name([parameter. List]) public static void main(string[] args) private double get. Price() private void set. Price(double a. Price) private String to. String()

Methods We will always provide the following 4 “types” of methods with our worker Methods We will always provide the following 4 “types” of methods with our worker classes: 1. constructor 2. mutator (modifier) 3. accessor 4. method that returns object state as a string

Methods Those are the 4 types of Standard method we will provide. They always Methods Those are the 4 types of Standard method we will provide. They always work with the class data fields. We will additionally then provide the specialized methods needed to perform our individual tasks: A method that calculates the unit price of an item

Constructor Always has same name as the class. Gets called automatically when you instantiate Constructor Always has same name as the class. Gets called automatically when you instantiate a class. If you do not provide one, one is automatically provided for you. Allows user of worker class to set initial values in the data fields

Mutators (modifiers) Allow the user to change the “state” of the object. Which means Mutators (modifiers) Allow the user to change the “state” of the object. Which means they can change the values in the data fields. Typically have 1 for each class data field and start with the word “set”. They are void, don’t return a value. Are passed a value (parameter) to store in data field.

Accessors Allow the user of you class to see or return the state (class Accessors Allow the user of you class to see or return the state (class data fields). Again typically have 1 for each data field. Typically begin with the word get. They always return a value (not void) Do not receive parameters

String to. String() converts the state of a class to a string. We will String to. String() converts the state of a class to a string. We will see some real neat outcomes of always providing this to. String() method. Always returns a value of type string.

Methods headers The order that the methods are programmed does not matter. By convention Methods headers The order that the methods are programmed does not matter. By convention we typically list constructors, mutators, accessors, to. String, then our class specific methods. See table of headers on page 109

Constructor method public Food. Item(String desc, double a. Size, double a. P) { description Constructor method public Food. Item(String desc, double a. Size, double a. P) { description = desc; size = a. Size; price = a. P; }

Mutator (modifier) public void set. Desc(String desc) { description = desc; } public void Mutator (modifier) public void set. Desc(String desc) { description = desc; } public void set. Size(double a. Size) { size = a. Size; } public void set. Price(double a. Price) { price = a. Price; }

Accessor public String get. Desc() { return description; } public double get. Size() { Accessor public String get. Desc() { return description; } public double get. Size() { return size; } public double get. Price() { return price; }

Return This is used to return a value to a calling program. Must use Return This is used to return a value to a calling program. Must use if not void. Tells compiler that the expression that follows is returned as the method result. Compiler assures that it is not possible to exit without returning a value. If possible get a syntax error.

to. String // postcondition: returns a string representing the item state public String to. to. String // postcondition: returns a string representing the item state public String to. String() { return description + ", size : " + size + ", price $" + price; }

Calling Methods Void methods are statements by themselves my. Candy. set. Description(“Snickers”); non-void you Calling Methods Void methods are statements by themselves my. Candy. set. Description(“Snickers”); non-void you must use value being returned “Price is $” + my. Candy. get. Price(); double price = my. Candy. get. Price();

Post conditions Each method should begin with a post condition comment. This is what Post conditions Each method should begin with a post condition comment. This is what must be true after the method executes. Is a part of the documentation.

Post Condition // postcondition: sets description to the argument value public void set. Desc(String Post Condition // postcondition: sets description to the argument value public void set. Desc(String desc) { description = desc; }

Post Condition // postcondition: returns the item price public double get. Price() { return Post Condition // postcondition: returns the item price public double get. Price() { return price; }

Parameters You can only access parameters within the body of the method they are Parameters You can only access parameters within the body of the method they are passed to. This is the “scope” of the method. Parameters are passed “respectively” They must match in type. See examples pg 114 -115

Test Class public class Test. Food. Item { public static void main(String[] args) { Test Class public class Test. Food. Item { public static void main(String[] args) { Food. Item my. Candy = new Food. Item("Snickers", 6. 5, 0. 55); Food. Item my. Soup = new Food. Item("Progresso Minestrone", 16. 5, 2. 35); System. out. println(my. Candy. to. String()); System. out. println(" -- unit price is $" + my. Candy. calc. Unit. Price()); System. out. println(my. Soup); System. out. println(" -- unit price is $" + my. Soup. calc. Unit. Price()); } }

Arguments Passed by value Primitive types are passed by value. If you change in Arguments Passed by value Primitive types are passed by value. If you change in method is not changed in calling program See example 3. 4 page 117 Objects are passed by reference.

Transfer of control When method is called control is passed to that method from Transfer of control When method is called control is passed to that method from the main method. When reaches end of method returns to main method. See example Figure 3. 5 on page 118.

Encapsulation Mutator methods change the state of the data fields. But to make those Encapsulation Mutator methods change the state of the data fields. But to make those changes the client (user) program must come through your methods. To retrieve a data fields must come through accessor. Your data is protected by encapsulation. See diagram pg 119

Section 3. 2 Class to manipulate Strings This section of the book create both Section 3. 2 Class to manipulate Strings This section of the book create both a worker (supporting) class and an application class.

Problem Program gets a sentence Displays first 3 words of the sentence on different Problem Program gets a sentence Displays first 3 words of the sentence on different lines. Sentence must have at least 4 words

Analysis Get first word of sentence Get rest of sentence also Then can get Analysis Get first word of sentence Get rest of sentence also Then can get first word of “rest of sentence” and so on See table 3. 3 top of page 121

Analysis Input – A sentence (at least 4 words) Output – first three words Analysis Input – A sentence (at least 4 words) Output – first three words of the sentence Need 2 classes – Worker class Word. Extractor must store sentence and get 1 st word and “rest” – Word. Extractor. App uses Word. Extractor to solve the problem.

Design Class Word. Extractor – Methods get. First() to get first word get. Rest() Design Class Word. Extractor – Methods get. First() to get first word get. Rest() to get rest of sentence – Your methods represent the actions you identify in analysis See figure 3. 7 page 121

Analysis Algorithm for get. First() – find position of the first blank in sentence Analysis Algorithm for get. First() – find position of the first blank in sentence – return characters up to the first blank Algorithm for get. Rest() – find position of the first blank in sentence – return characters after the first blank

Analysis Application class (Word. Extractor) always contains main method where program execution begins. Can Analysis Application class (Word. Extractor) always contains main method where program execution begins. Can solve this by creating 3 word extractor objects. 1 st one original sentence 2 nd “rest” and so on

Algorithm for main() Read in Sentence. Create Word. Extractor object that stores input sentence. Algorithm for main() Read in Sentence. Create Word. Extractor object that stores input sentence. Write first word in console window. Create new Word. Extractor object that stores sentence starting with second word. ……………

Implementation Each class gets defined in it’s own file. Is it’s own project in Implementation Each class gets defined in it’s own file. Is it’s own project in JBuilder. Class Word. Extractor has a single field – sentence whose first word is being retrieved – Use String class index. Of() substring()

Some details int pos. Blank = sentence. index. Of(“ “); – pos. Blank is Some details int pos. Blank = sentence. index. Of(“ “); – pos. Blank is a variable but is not a class data field. – pos. Blank is a local variable to the method it is declared in. – Can only be accessed in this method. – This is known as variable scope.

Some details return sentence. substring(0, pos. Blank); returns String object containing characters of first Some details return sentence. substring(0, pos. Blank); returns String object containing characters of first word. return sentence. substring(pos. Blank + 1); return String object containing rest of sentence.

Some details String sent = JOption. Pane. show. Input. Dialog(“enter at least 4 words”); Some details String sent = JOption. Pane. show. Input. Dialog(“enter at least 4 words”); Word. Extractor w. E 1 = new Word. Extractor(sent);

Code Look at code pages 124 – 125 Look at running in JBuilder Code Look at code pages 124 – 125 Look at running in JBuilder

Program style Program choose to use multiple objects versus 1 object solution. Will be Program style Program choose to use multiple objects versus 1 object solution. Will be easier to design 1 object solution once we know about looping. Notice worker class did not have appropriate constructor, mutator, and accessor methods.

Section 3. 3 Worker class for integers Problem – Program takes number of coins Section 3. 3 Worker class for integers Problem – Program takes number of coins and converts it into total amount. Analysis – Computes the value in dollars and cents

Data Input – Number of pennies – Number of nickels – Number of dimes Data Input – Number of pennies – Number of nickels – Number of dimes – Number of quarters Output – Value if coins in dollars and change

Design See table on page 129 Design See table on page 129

Implementation Review code pages 130 – 132 Look at running in Jbuilder Show bad Implementation Review code pages 130 – 132 Look at running in Jbuilder Show bad result if – 5, 5, 5, 5 (shows 2. 5 bad formatting) – needs to be 2. 05

Program Style Store only essential data in object – tendency is to want to Program Style Store only essential data in object – tendency is to want to store the total value. Calculate it once, and store it. – Object oriented approach does not do this. Values that can be calculated are not stored.

Section 3. 4 Review of Methods Constructor Methods – same name as class – Section 3. 4 Review of Methods Constructor Methods – same name as class – initializes class data items – If you don’t provide on java provides one – Sets data items to values shown on page 134 – See 2 appropriate ones top of page 135

Accessor Methods Users can not access data items directly when they are private If Accessor Methods Users can not access data items directly when they are private If the user needs access to these values you must provide accessor methods to allow them to retrieve the values. See example bottom page 135

Mutator Methods If users needs ability to change class data items you must provide Mutator Methods If users needs ability to change class data items you must provide that also. See top of page 136

String objects are immutable You can not change the characters in a string. Run String objects are immutable You can not change the characters in a string. Run code on page 136 in JBuilder.

Calling one instance method from another In Coin. Changer the method find. Dollars() calls Calling one instance method from another In Coin. Changer the method find. Dollars() calls the method find. Cents. Value() which is also in Coin. Changer. It does not specify an object to apply the method to. Which object does it use? ?

this prefix Can be used to point to the correct data field public void this prefix Can be used to point to the correct data field public void set. Pennies(int pennies) { this. pennies = pennies; } Makes this. pennies refer to the data field pennies not the parameter pennies.

Class methods versus instance methods Class methods use the keyword static. Class methods manipulate Class methods versus instance methods Class methods use the keyword static. Class methods manipulate data passed as an argument. Do not have data fields. Class methods are not applied to an object.

Program Style Minimize use of local variables. – Read in data and pass directly Program Style Minimize use of local variables. – Read in data and pass directly to appropriate methods c. C. set. Pennies(read. Int(“Number of pennies”)); Reduces need for local storage. See static read. Int on page 139

Section 3. 5 using multiple classes This Case study looks at using 2 worker Section 3. 5 using multiple classes This Case study looks at using 2 worker classes rather than one. This approach will often simplify the solution to a problem. It is a perfectly valid approach. Most libraries use multiple classes.

Problem Need to compute weight of a batch of washers. First step is to Problem Need to compute weight of a batch of washers. First step is to calculate the rim area of a washer. This is simply the area of the inner circle subtracted from the outer circle area.

Washer Area of inner circle is r 2 Area of the outer (big) circle Washer Area of inner circle is r 2 Area of the outer (big) circle is r 2 Area of the rim is just the outer circle area minus the inner circle area.

Computing rim area So to compute the rim area we simply subtract the area Computing rim area So to compute the rim area we simply subtract the area of the small inner circle from the big outer circle. So a washer from a data standpoint is really 2 circles. So in order to break this down into the associated real world elements we start with a circle class.

Design See tables of data fields and methods on pages 143 – 144. Look Design See tables of data fields and methods on pages 143 – 144. Look at code in JBuilder and pages 145 – 148.

Section 3. 6 Can use existing classes to properly format our output. Can also Section 3. 6 Can use existing classes to properly format our output. Can also use existing classes to assist with proper input.

Class Decimal Format import java. text. decimal. Format Allows us to format decimal numbers Class Decimal Format import java. text. decimal. Format Allows us to format decimal numbers 0 displays leading zeroes # does not See specification of number top of page 151

Class Number. Format Can use this to format specific types of output. See table Class Number. Format Can use this to format specific types of output. See table bottom of page 152

Class Key. In They took the read. Int and read. Double we looked at Class Key. In They took the read. Int and read. Double we looked at and put them in their own library for re-use. If you care to use this the source code is on the P: drive for re-use Must compile the code before use See table bottom of page 153

Introduction to comp graphics Drawing surface – Picture as x-y grid with 0, 0 Introduction to comp graphics Drawing surface – Picture as x-y grid with 0, 0 being top left hand corner. Java has a class library (AWT) for graphics and GUI design – A newer version (swing) exists Must import AWT for use

Applets Not self sufficient 3 files need to be in same directory – HTML Applets Not self sufficient 3 files need to be in same directory – HTML file –. class –. java (if allow for viewing via link) HTML file needs applet tag

Intersection applet Pg 159 2 imports (typically use both) Extends applet Initial method is Intersection applet Pg 159 2 imports (typically use both) Extends applet Initial method is paint – Event driven g. set. Color(Color. black); g. draw. Line(0, 0, 300, 200); drawline method See Color constants top Pg 160

Drawing rectangles draw. String (“string”, x, y) draw. Rect (x, y, w, l) – Drawing rectangles draw. String (“string”, x, y) draw. Rect (x, y, w, l) – x, y coordinate top left – w, l width and length fill. Rect use Pg 162 See house code Pg 162

Other shapes draw. Arc(x, y, rw, rl, ab, ae) See page 164 draw. Oval(x, Other shapes draw. Arc(x, y, rw, rl, ab, ae) See page 164 draw. Oval(x, y, 100) – x, y circle center – Bounded by a square 100 x 100 Happy Face

Pie slices fill. Arc for pie slices See page 163 for a summary of Pie slices fill. Arc for pie slices See page 163 for a summary of graphics methods.

Common programming errors Review bulleted items pages 170 - 172 Common programming errors Review bulleted items pages 170 - 172