chapter 3 object oriented design and writing worker classes
Post on 21-Dec-2015
242 views
TRANSCRIPT
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
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. A Header declaration
2. The class bodya. 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. 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. The FoodItem fields are:
public class FoodItem {// data fieldsprivate String description;private double size;private double price;
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 be accessed via the class methods.
Syntax Diagram:[visibility] typeName datafieldName = [value];
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 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 name and parameters and return value which are both optional.
Syntax Diagram
visibility [static] resultType methodName([parameterList])
public static void main(string[] args)
private double getPrice()
private void setPrice(double aPrice)
private String toString()
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
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 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 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 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 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.
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
Constructor method
public FoodItem(String desc, double aSize, double aP)
{
description = desc;
size = aSize;
price = aP;
}
Mutator (modifier)public void setDesc(String desc) { description = desc; } public void setSize(double aSize) { size = aSize; } public void setPrice(double aPrice) { price = aPrice; }
Accessor public String getDesc() { return description; } public double getSize() { return size; } public double getPrice() { return price; }
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.
toString
// postcondition: returns a string representing the item state
public String toString() {
return description + ", size : " + size +
", price $" + price;
}
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();
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 setDesc(String desc)
{
description = desc;
}
Post Condition
// postcondition: returns the item price
public double getPrice() {
return price;
}
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 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()); }}
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 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 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 a worker (supporting) class and an application class.
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 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 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.
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
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
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
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.
……………
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()
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.
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.
Some details
String sent =
JOptionPane.showInputDialog(“enter at least 4 words”);
WordExtractor wE1 = new WordExtractor(sent);
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 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 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– Number of quarters
Output– Value if coins in dollars and change
Design See table on page 129
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 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– 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 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 that also. See top of page 136
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 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??
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.
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 to appropriate methods
cC.setPennies(readInt(“Number of pennies”));
Reduces need for local storage. See static readInt on page 139
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 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 r2
Area of the outer (big) circle is r2
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 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 at code in JBuilder and pages 145 – 148.
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.decimalFormat Allows us to format decimal numbers 0 displays leading zeroes # does not See specification of number top of
page 151
Class NumberFormat Can use this to format specific types of
output. See table bottom of page 152
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
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 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 paint
– Event driven g.setColor(Color.black); g.drawLine(0, 0, 300, 200); drawline method See Color constants top Pg 160
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
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
Pie slices fillArc for pie slices See page 163 for a summary of
graphics methods.
Common programming errors
Review bulleted items pages 170 - 172