chapter 3 object oriented design and writing worker classes

76
Chapter 3 Object Oriented Design and Writing Worker Classes

Post on 21-Dec-2015

242 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 3 Object Oriented Design and Writing Worker Classes

Chapter 3

Object Oriented Design and Writing Worker Classes

Page 2: Chapter 3 Object Oriented Design and Writing Worker Classes

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

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

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.

Page 4: Chapter 3 Object Oriented Design and Writing Worker Classes

Review of class definitions

1. A Header declaration

2. The class bodya. The data field declarations of the class

b. The method definitions of the class

Page 5: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 6: Chapter 3 Object Oriented Design and Writing Worker Classes

Class Data Field The values in these fields represent the

“state” of the object. The FoodItem fields are:

public class FoodItem {// data fieldsprivate String description;private double size;private double price;

Page 7: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 8: Chapter 3 Object Oriented Design and Writing Worker Classes

Class Data Fields Because we make our class data

fields private they can only be accessed via the class methods.

Syntax Diagram:[visibility] typeName datafieldName = [value];

Page 9: Chapter 3 Object Oriented Design and Writing Worker Classes

Visibility 4 types of visibility exist:

– private (only class)– public (anywhere)– protected (class and subclasses)– default (package (in same folder))

Page 10: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 11: Chapter 3 Object Oriented Design and Writing Worker Classes

Method Definitions Form:

method header {method body

}

The header gives the method name and parameters and return value which are both optional.

Page 12: Chapter 3 Object Oriented Design and Writing Worker Classes

Syntax Diagram

visibility [static] resultType methodName([parameterList])

public static void main(string[] args)

private double getPrice()

private void setPrice(double aPrice)

private String toString()

Page 13: Chapter 3 Object Oriented Design and Writing Worker Classes

Methods Methods We will always provide the following 4

“types” of methods with our worker classes:1. constructor2. mutator (modifier)3. accessor4. method that returns object state as a string

Page 14: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 15: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 16: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 17: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 18: Chapter 3 Object Oriented Design and Writing Worker Classes

String toString() converts the state of a class

to a string. We will see some real neat outcomes

of always providing this toString() method.

Always returns a value of type string.

Page 19: Chapter 3 Object Oriented Design and Writing Worker Classes

Methods headers The order that the methods are

programmed does not matter. By convention we typically list

constructors, mutators, accessors, toString, then our class specific methods.

See table of headers on page 109

Page 20: Chapter 3 Object Oriented Design and Writing Worker Classes

Constructor method

public FoodItem(String desc, double aSize, double aP)

{

description = desc;

size = aSize;

price = aP;

}

Page 21: Chapter 3 Object Oriented Design and Writing Worker Classes

Mutator (modifier)public void setDesc(String desc) { description = desc; } public void setSize(double aSize) { size = aSize; } public void setPrice(double aPrice) { price = aPrice; }

Page 22: Chapter 3 Object Oriented Design and Writing Worker Classes

Accessor public String getDesc() { return description; } public double getSize() { return size; } public double getPrice() { return price; }

Page 23: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 24: Chapter 3 Object Oriented Design and Writing Worker Classes

toString

// postcondition: returns a string representing the item state

public String toString() {

return description + ", size : " + size +

", price $" + price;

}

Page 25: Chapter 3 Object Oriented Design and Writing Worker Classes

Calling Methods Void methods are statements by

themselves

myCandy.setDescription(“Snickers”); non-void you must use value being

returned

“Price is $” + myCandy.getPrice();

double price = myCandy.getPrice();

Page 26: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 27: Chapter 3 Object Oriented Design and Writing Worker Classes

Post Condition

// postcondition: sets description to the argument value

public void setDesc(String desc)

{

description = desc;

}

Page 28: Chapter 3 Object Oriented Design and Writing Worker Classes

Post Condition

// postcondition: returns the item price

public double getPrice() {

return price;

}

Page 29: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 30: Chapter 3 Object Oriented Design and Writing Worker Classes

Test Classpublic class TestFoodItem {

public static void main(String[] args) { FoodItem myCandy = new FoodItem("Snickers", 6.5, 0.55); FoodItem mySoup = new FoodItem("Progresso Minestrone", 16.5,

2.35); System.out.println(myCandy.toString()); System.out.println(" -- unit price is $" + myCandy.calcUnitPrice()); System.out.println(mySoup); System.out.println(" -- unit price is $" + mySoup.calcUnitPrice()); }}

Page 31: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 32: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 33: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 34: Chapter 3 Object Oriented Design and Writing Worker Classes

Section 3.2 Class to manipulate Strings

This section of the book create both a worker (supporting) class and an application class.

Page 35: Chapter 3 Object Oriented Design and Writing Worker Classes

Problem Program gets a sentence Displays first 3 words of the sentence

on different lines. Sentence must have at least 4 words

Page 36: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 37: Chapter 3 Object Oriented Design and Writing Worker Classes

Analysis Input

– A sentence (at least 4 words) Output

– first three words of the sentence Need 2 classes

– Worker class WordExtractor must store sentence and get 1st word and “rest”

– WordExtractorApp uses WordExtractor to solve the problem.

Page 38: Chapter 3 Object Oriented Design and Writing Worker Classes

Design Class WordExtractor

– Methods getFirst() to get first word getRest() to get rest of sentence

– Your methods represent the actions you identify in analysis

See figure 3.7 page 121

Page 39: Chapter 3 Object Oriented Design and Writing Worker Classes

Analysis Algorithm for getFirst()

– find position of the first blank in sentence– return characters up to the first blank

Algorithm for getRest()– find position of the first blank in sentence– return characters after the first blank

Page 40: Chapter 3 Object Oriented Design and Writing Worker Classes

Analysis Application class (WordExtractor)

always contains main method where program execution begins.

Can solve this by creating 3 word extractor objects.

1st one original sentence 2nd “rest” and so on

Page 41: Chapter 3 Object Oriented Design and Writing Worker Classes

Algorithm for main() Read in Sentence. Create WordExtractor object that

stores input sentence. Write first word in console window. Create new WordExtractor object that

stores sentence starting with second word.

……………

Page 42: Chapter 3 Object Oriented Design and Writing Worker Classes

Implementation Each class gets defined in it’s own file. Is it’s own project in JBuilder. Class WordExtractor has a single field

– sentence whose first word is being retrieved

– Use String class indexOf() substring()

Page 43: Chapter 3 Object Oriented Design and Writing Worker Classes

Some details int posBlank = sentence.indexOf(“ “);

– posBlank is a variable but is not a class data field.

– posBlank is a local variable to the method it is declared in.

– Can only be accessed in this method.– This is known as variable scope.

Page 44: Chapter 3 Object Oriented Design and Writing Worker Classes

Some details return sentence.substring(0,

posBlank); returns String object containing

characters of first word. return sentence.substring(posBlank +

1); return String object containing rest of

sentence.

Page 45: Chapter 3 Object Oriented Design and Writing Worker Classes

Some details

String sent =

JOptionPane.showInputDialog(“enter at least 4 words”);

WordExtractor wE1 = new WordExtractor(sent);

Page 46: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 47: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 48: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 49: Chapter 3 Object Oriented Design and Writing Worker Classes

Data Input

– Number of pennies– Number of nickels– Number of dimes– Number of quarters

Output– Value if coins in dollars and change

Page 50: Chapter 3 Object Oriented Design and Writing Worker Classes

Design See table on page 129

Page 51: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 52: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 53: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 54: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 55: Chapter 3 Object Oriented Design and Writing Worker Classes

Mutator Methods If users needs ability to change class

data items you must provide that also. See top of page 136

Page 56: Chapter 3 Object Oriented Design and Writing Worker Classes

String objects are immutable

You can not change the characters in a string.

Run code on page 136 in JBuilder.

Page 57: Chapter 3 Object Oriented Design and Writing Worker Classes

Calling one instance method from another

In CoinChanger the method findDollars() calls the method findCentsValue() which is also in CoinChanger.

It does not specify an object to apply the method to.

Which object does it use??

Page 58: Chapter 3 Object Oriented Design and Writing Worker Classes

this prefix Can be used to point to the correct

data fieldpublic void setPennies(int pennies) {

this.pennies = pennies; } Makes this.pennies refer to the data

field pennies not the parameter pennies.

Page 59: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 60: Chapter 3 Object Oriented Design and Writing Worker Classes

Program Style Minimize use of local variables.

– Read in data and pass directly to appropriate methods

cC.setPennies(readInt(“Number of pennies”));

Reduces need for local storage. See static readInt on page 139

Page 61: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 62: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 63: Chapter 3 Object Oriented Design and Writing Worker Classes

Washer

Area of inner circle is r2

Area of the outer (big) circle is r2

Area of the rim is just the outer circle area minus the inner circle area.

Page 64: Chapter 3 Object Oriented Design and Writing Worker Classes

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.

Page 65: Chapter 3 Object Oriented Design and Writing Worker Classes

Design See tables of data fields and methods

on pages 143 – 144.

Look at code in JBuilder and pages 145 – 148.

Page 66: Chapter 3 Object Oriented Design and Writing Worker Classes

Section 3.6 Can use existing classes to properly

format our output. Can also use existing classes to assist

with proper input.

Page 67: Chapter 3 Object Oriented Design and Writing Worker Classes

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

page 151

Page 68: Chapter 3 Object Oriented Design and Writing Worker Classes

Class NumberFormat Can use this to format specific types of

output. See table bottom of page 152

Page 69: Chapter 3 Object Oriented Design and Writing Worker Classes

Class KeyIn They took the readInt and readDouble

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

Page 70: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 71: Chapter 3 Object Oriented Design and Writing Worker Classes

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

Page 72: Chapter 3 Object Oriented Design and Writing Worker Classes

Intersection applet Pg 159

2 imports (typically use both) Extends applet Initial method is paint

– Event driven g.setColor(Color.black); g.drawLine(0, 0, 300, 200); drawline method See Color constants top Pg 160

Page 73: Chapter 3 Object Oriented Design and Writing Worker Classes

Drawing rectangles drawString (“string”, x, y) drawRect (x, y, w, l)

– x, y coordinate top left– w, l width and length

fillRect use Pg 162 See house code Pg 162

Page 74: Chapter 3 Object Oriented Design and Writing Worker Classes

Other shapes drawArc(x, y, rw, rl, ab, ae) See page 164 drawOval(x, y, 100, 100)

– x, y circle center– Bounded by a square 100 x 100

Happy Face

Page 75: Chapter 3 Object Oriented Design and Writing Worker Classes

Pie slices fillArc for pie slices See page 163 for a summary of

graphics methods.

Page 76: Chapter 3 Object Oriented Design and Writing Worker Classes

Common programming errors

Review bulleted items pages 170 - 172