copyright 2003 pearson education, inc. slide 3-1 chapter outline 3.1a first worker class: class...

67
Copyright © 2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1 A First Worker Class: Class FoodItem 3.2 A Worker Class that Processes String Objects • Case Study: Finding the Words in a Sentence 3.3 A Worker Class that Processes Integers • Case Study: Designing a Coin Changer Machine 3.4 Review of Method Categories 3.5 Simplifying a Solution Using Multiple Classes • Case Study: Computing the Weight of Flat Washers 3.6 Formatting Output and Class KeyIn (Optional) 3.7 Applets, AWT, and the Graphics Class (Optional)

Upload: preston-thompson

Post on 18-Jan-2018

214 views

Category:

Documents


0 download

DESCRIPTION

Copyright © 2003 Pearson Education, Inc. Slide 3-3 Data field declarations in FoodItem These data field declarations resemble variable declarations except they begin with the visibility modifier private. A private data field can be accessed directly in the class in which it is defined, but not outside the class. Other classes can manipulate data field price, for example, only through the methods of class FoodItem. public class FoodItem { // data fields private String description; private double size; private double price;

TRANSCRIPT

Page 1: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-1

Chapter Outline

• 3.1 A First Worker Class: Class FoodItem• 3.2 A Worker Class that Processes String Objects

• Case Study: Finding the Words in a Sentence• 3.3 A Worker Class that Processes Integers

• Case Study: Designing a Coin Changer Machine• 3.4 Review of Method Categories • 3.5 Simplifying a Solution Using Multiple Classes

• Case Study: Computing the Weight of Flat Washers

• 3.6 Formatting Output and Class KeyIn (Optional)• 3.7 Applets, AWT, and the Graphics Class (Optional)

Page 2: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-2

3.1 Review of Class Definitions

• The data fields of a class (also called instance variables) store the information associated with an object of that class. The data fields may be referenced throughout the class. The values stored in an object's data fields represent the state of that object.

• The methods specify the operations that objects of the class can peform.

1. Class header 2. Class body 2.1 The data field declarations for the class 2.2 The method definitions of the class

We design worker classes or support classes that support the application class or client class .

Page 3: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-3

Data field declarations in FoodItem

• These data field declarations resemble variable declarations except they begin with the visibility modifier private.

• A private data field can be accessed directly in the class in which it is defined, but not outside the class.

• Other classes can manipulate data field price, for example, only through the methods of class FoodItem.

public class FoodItem {

// data fields private String description; private double size; private double price;

Page 4: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-4

Sytnax for Data field Declaration

• Form: [visibility] typeName datafieldName = [value];Example: private int pennies;private String month;

• Interpretation: The data type of datafieldName is specified as typeName where typeName is a predefined Java type or a class that has been defined by Java programmers. If value is present, it must be a literal of data type typeName. The visibility may be specified as private (accessible only within the class), public (accessible anywhere), or protected (accessible only within the class and by subclasses of the class). If omitted, it has default visibility which means it can be accessed by any class in the same folder as the current class.

Page 5: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-5

Method Definitions

public static void main(String[] args) { System.out.println("Hello world"); System.out.println("Java is fun");}

Method definitions have the form

method header { method body} parameters

bodyheader

Page 6: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-6

Method Header

• The method header gives the method name, the data type of the value returned by the method (if any), and its parameters in parentheses.Form: visibility [static] resultType methodName ([parameterList])Examples: public static void main(String[] args) public double getPrice() public void setPrice(double aPrice)

• Interpretation: The type of result returned is resultType where void means the method does not return a result. The method parameters appear in the parameterList. This list contains individual data declarations (data type, identifier pairs) separated by commas. Empty parentheses () indicate that a method has no parameters.

Page 7: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-7

Method header, cont’d.

• The method definition specifies visibility with modifier keywords (for example, public, private) that precede the resultType. The visibility specifies whether the method may be called from outside the class (public visibility) or just within the class (private visibility). Most methods we write have public visibility.

• The keyword static indicates that a method is a class method, not an instance method. Most methods we write are instance methods.

Page 8: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-8

Methods for Class FoodItem

• For most classes, we need to provide methods that perform tasks similar to the ones below.

• a method to create a new FoodItem object with a specified description, size, and price (constructor)

• methods to change the description, size, or price of an existing FoodItem object (mutators)

• methods that return the description, size, or price of an existing FoodItem object (accessors)

• a method that returns the object state as a string (a toString() method).

Page 9: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-9

Method Headers for Class FoodItem

Methodpublic

FoodItem(String, double, double)

public void setDesc(String)

public void setSize(double)

Description• Constructor - creates a new

object whose three data fields have the values specified by its three arguments.

• Mutator - sets the value of data field description to the value indicated by its argument. Returns no value.

• Mutator - sets the value of data field size to the value indicated by its argument. Returns no value.

Page 10: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-10

Method Headers for Class FoodItem, cont’d.

Methodpublic void

setPrice(double)

public String getDesc()

public double getSize()

Description• Mutator - sets the value of

data field price to the value indicated by its argument. Returns no value.

• Accessor - returns a reference to the string referenced by data field description.

• Accessor - returns the value of data field size.

Page 11: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-11

Method Headers for Class FoodItem, cont’d.

Methodpublic double

getPrice()

public String toString()

public double calcUnitPrice()

Description• Accessor - returns the value

of data field price.

• Returns a string representing the state of this object.

• Returns the unit price (price / size) of this item.

Page 12: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-12

Class FoodItem

/* * FoodItem.java Author: Koffman and Wolz * Represents a food item at a market */public class FoodItem {

// data fields private String description; private double size; private double price;

Page 13: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-13

Class FoodItem, cont’d.

// methods // postcondition: creates a new object with data // field values as specified by the arguments public FoodItem(String desc, double aSize,

double aPrice) { description = desc; size = aSize; price = aPrice; }

// postcondition: sets description to argument // value public void setDesc(String desc) { description = desc; }

Page 14: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-14

Class FoodItem, cont’d.

// postcondition: sets size to argument value public void setSize(double aSize) { size = aSize; }

// postcondition: sets price to argument value public void setPrice(double aPrice) { price = aPrice; }

// postcondition: returns the item description public String getDesc() { return description; }

// postcondition: returns the item size public double getSize() { return size; }

Page 15: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-15

Class FoodItem, cont’d.

// postcondition: returns the item price public double getPrice() { return price; }

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

// postcondition: calculates & returns unit price public double calcUnitPrice() { return price / size; } }

Page 16: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-16

void Methods

• The mutator methods are void methods.

• Method setSize() sets the value of data field size to the value passed to parameter aSize.

• A void method is executed for its effect because it does not return a value; however, it may change the state of an object or cause some information to be displayed.

public void setSize(double aSize) { size = aSize; }

Page 17: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-17

The return Statement

• Each FoodItem method that is not a void method or a constructor returns a single result.

The return statement above returns the value of data field price as the function result.

• Form: return expression;• Example: return x + y;• Interpretation: The expression after the keyword return is returned as

the method result. Its data type must be assignment compatible with the type of the method result.

public double getPrice() { return price; }

Page 18: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-18

toString() Method

• A toString() method returns a reference to a String object that represents an object's state.

The expression after return specifies the characters stored in the String object returned as the method result. It starts with the characters in description followed by the characters , size : followed by characters representing the value of data field size and price; e.g.,

"apples, Macintosh, size: 2.5, price $1.25"

public String toString() { return description + ", size : " + size + ", price $" + price; }

Page 19: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-19

Calling methods

• Because a void method does not return a value, a call to a void method is a Java statement all by itself. If myCandy is type FoodItem, an example would be

• Because a non-void method returns a value, a call to a non-void method must occur in an expression:

• The result returned by the call to method getPrice() (type double) is appended to the string that starts with the characters price is $

myCandy.setDescription("Snickers, large");

"price is $" + myCandy.getPrice()

Page 20: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-20

Call to Constructor

• A constructor executes when a new object is created and initializes the object’s data fields. A call to this constructor always follows the word new and has the form:

public FoodItem(String desc, double aSize, double aPrice) { description = desc; size = aSize; price = aPrice;}

FoodItem myCandy = new FoodItem("Snickers", 6.5, 0.55);

Page 21: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-21

Argument/Parameter Correspondence for FoodItem("Snickers", 6.5, 0.55)

Argument"Snickers"

6.5

0.55

Parameterdesc (references "Snickers")

aSize (value is 6.5)

aPrice (value is 0.55)

Primitive type arguments are passed by value which means the method cannot change the argument value.

Page 22: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-22

Testing the class FoodItem

client (application) class

TestFoodItem

main()

FoodItem

FoodItem()setDesc()setSize()setPrice()getDesc()getSize()getPrice()calcUnitPrice()toString()

description: Stringsize: doubleprice: double

associationrelationship

worker class

UML class diagram

Program classes and their relationships

return from method

(optional)

UML sequence diagram

TestFoodItem

myCandy: FoodItem

new()

new()

toString()

mySoup: FoodItem

calculateUnitPrice()

toString()

calculateUnitPrice()

Collaboration between objects (classes) at runtime

classes/ objects

creation of a new object

method call

method execution

time

axis object

lifeline

Page 23: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-23

Application or Client of FoodItem

/* * TestFoodItem.java Author: Koffman and Wolz * Tests class FoodItem */public 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.toString()); System.out.println(" -- unit price is $" + mySoup.calcUnitPrice()); }}

Page 24: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-24

Sample Run of Class TestFoodItem

Page 25: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-25

3.2 Finding Words in a Sentence

• PROBLEM: We want to write a program that gets a sentence and displays the first three words in the sentence on separate lines. To simplify the task, we assume that the sentence has at least 4 words.

Page 26: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-26

DESIGN of Application Class

• Algorithm for main()1. Read in a sentence.2. Create a WordExtractor object that stores the input sentence.3. Write the first word to the console window.4. Create a WordExtractor object that stores the sentence starting

with the second word.5. Write the second word to the console window.6. Create a WordExtractor object that stores the sentence starting

with the third word.7. Write the third word to the console window.8. Write the rest of the sentence to the console window.

Page 27: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-27

UML sequence diagram

WordExtractorApp JOptionPane

showInputDialog()

getFirst()

System.out

wE1: WordExtractor

new()

println()

get sentence

create wE1, get first word and display it

display rest of the sentence

getRest()

getFirst()

wE2: WordExtractor

new()

println()getRest()

wE3: WordExtractor

getFirst()

new()

println()getRest()println()

create wE2, get next word and display it

create wE3, get next word and display it

Page 28: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-28

Program Style: Using Multiple Objects versus Reusing One

– There is usually more than one way to solve a problem. Because class WordExtractorApp needed to extract three words, we decided to use multiple objects of type WordExtractor. When we create each object, we pass the constructor a different string to be stored. Consequently, when we apply methods getFirst() and getRest() to each object, we get a different result.

– We could have used just one object. We could use method setSentence() to update its value after extracting each word Neither solution is "better"; they are just different approaches.

Question to ponder: Rewrite WordExtractorApp using just object wE1.

Page 29: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-29

3.3 A Worker Class that Processes Integers

PROBLEM A common problem is to determine the value of a collection of coins. Our goal is to write a class that simulates the behavior of a coin changing machine. Instead of pouring a container of coins into a hopper, the user will provide the number of each kind of coin as input data.

Page 30: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-30

ANALYSIS

• The first step is to determine what a coin-changing machine must do. It accepts a collection of coins and computes the value of the coins in dollars and cents. For example, if a collection contains 5 quarters and 3 pennies, its value is $1.28 (one dollar and 28 cents in change). The problem inputs are the number of each kind of coin and the problem output is the value of the coins in dollars and change.

• Data RequirementsProblem Inputs Problem Output

the number of pennies value of coins in dollars and change

the number of nickels Relevant Formulas the number of dimes value of a penny is 1 cent the number of quarters value of a nickel is 5 cents

value of a dime is 10 centsvalue of a quarter is 25 centsvalue of a dollar is 100 cents

Page 31: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-31

DESIGN: UML class diagram

UML class diagrams describe the program structure, i.e. the classes and their relationships.The execution of a program can be described by using UML sequence diagrams.

ChangeCoinApp

main()

JOptionPanefrom javax.swing

readDouble()readInt()…

CoinChanger

setPennies()setNickels()setDimes()setQuarters()findCentValues()findDollars()toString()

pennies: intnickels: intdimes: intquarters: int

class imported from javax.swing package

associationrelationships class name

data fields or attributes

methods or operations

worker class

application class

Page 32: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-32

UML sequence diagram

method call from another object

internal method call

internal method execution

WasherAppl

new()

setPennies()

JOptionPane

readInt()showInputDialog()

readInt()showInputDialog()

readInt()

showInputDialog()

readInt()showInputDialog()

changer: CoinChanger

setNickels()

setDimes()

setQuarters()

findDollars()

findCentValues()

showMessageDialog()

get number of pennies

get number of nickels

get number of dimes

get number of quarters

compute dollars and change

display results

notes for comments

findChange()

object

focus of control (represents the method execution)

object life line

findCentValues()

create new object

Page 33: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-33

Design of Class CoinChanger

Data fieldsint penniesint nickelsint dimesint quarters

methodsvoid setPennies(int)void setNickels(int)void setDimes(int)void setQuarters(int)int findCentsValue(intint findDollars()int findChange()String toString()

Attributescount of penniescount of nickelscount of dimescount of quarters

BehaviorSets the count of pennies.Sets the count of nickels.Sets the count of dimes.Sets the count of quarters.Calculates total value in cents.Calculates value in dollars.Calculates leftover change.Represents object's state.

Page 34: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-34

Algorithms for CoinChanger methods

Algorithm for setPennies()1. Store the number of pennies.

Algorithm for findCentsValue()1. Calculate the total value in cents using the formula total cents = pennies + 5 nickels

+10 dimes + 25 quarters

Algorithm for findDollars()1. Get the integer quotient of the total value in cents divided by 100 (for example, the

integer quotient of 327 divided by 100 is 3).

Algorithm for findChange()1. Get the integer remainder of the total value in cents divided by 100 (for example, the

integer remainder of 327 divided by 100 is 27)..

Algorithm for toString()1. Represent the state of the object (the number of each kind of coin).

Page 35: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-35

Implementation of CoinChanger/* * CoinChanger.java Author: Koffman and Wolz * Represents a coin changer */public class CoinChanger { // Data fields private int pennies; private int nickels; private int dimes; private int quarters;

// Methods public void setPennies(int pen) { pennies = pen; }

public void setNickels(int nick) { nickels = nick; }

public void setDimes(int dim) { dimes = dim; }

public void setQuarters(int quart) { quarters = quart; }

Page 36: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-36

Implementation of CoinChanger, cont’d.

// postcondition: Returns the total value in cents. public int findCentsValue() { return pennies + 5 * nickels + 10 * dimes + 25 * quarters; }

// postcondition: Returns the amount in dollars. public int findDollars() { return findCentsValue() / 100; }

// postcondition: Returns the amount of leftover // change. public int findChange() { return findCentsValue() % 100; }

public String toString() { return pennies + " pennies, " + nickels + " nickels, " + dimes + " dimes, " + quarters + " quarters"; }}

Page 37: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-37

Design of ChangeCoinsApp

methodmain

Classes usedCoinChanger, JOptionPane

behaviorGets the number of each kind of coin,

stores this information in a CoinChanger object, calculates and displays the value of coins in dollars and change.

Algorithm for main() 1. Create a CoinChanger object.2. Store the number of each kind of coin in the CoinChanger object.3. Display the value of the coins in dollars and change.

Page 38: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-38

3.4 Review of Methods

• Default initialization of new object by Constructor

Data Field Type Default valueint zerodouble zeroboolean falsechar The first character in the Unicode

character set (called the null character)

a class type null

Page 39: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-39

Two constructors for CoinChanger

public CoinChanger() {}

public CoinChanger(int pen, int nick, int dim, int quar) { pennies = pen; nickels = nick; dimes = dim; quarters = quar;}

No parameter constructor (default)

If you write one or more constructors for a class, the compiler will not provide a default constructor, so you must define it yourself if you need it. When a new CoinChanger object is created, the argument list used in the constructor call determines which constructor is invoked.

Page 40: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-40

Calling one Instance Method from Another

• Method findDollars() (new method in class CoinChanger) calls method findCentsValue() (also defined in class CoinChanger). Notice that instance method findCentsValue() is not applied to any object. The default is the current object which can be represented by the keyword this; e.g.,

// postcondition - returns coin value in dollarspublic int findDollars() { return findCentsValue() / 100;}

return this.findCentsValue() / 100;

Page 41: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-41

Use of Prefix this with a Data Field

// Mutator // Stores argument value in data field pennies. public void setPennies(int pennies) { this.pennies = pennies; }

Refers to data field pennies

Refers to argument pennies

Note: the local declaration of pennies as a parameterin method setPennies() hides data field penniesin this method. Hence, the need for keyword this to reference the data field.

Page 42: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-42

3.6 Simplifying a Solution UsingMultiple Classes

PROBLEMYou work for a hardware company that manufactures flat washers. To estimate shipping costs, you need a program that computes the weight of a specified quantity of flat washers. As part of this process, you need to compute the weight of a single washer.

Page 43: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-43

ANALYSIS

• A flat washer resembles a small donut. To compute its weight you need its rim area, thickness, and the density of the material used in its construction. The thickness and density of a washer are available as input data.

• The rim area must be calculated from the washer's inner diameter ( ) and the washer's outer diameter ( ) which are both data items. The number of washers is an input.

Page 44: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-44

ANALYSIS, cont’d.

Data RequirementsProblem Inputs Problem Outputs

inner radius weight of batch of washersouter radiusthicknessdensityquantity

Relevant formulasarea of circle= x radius2

perimeter of circle = 2 x x radius

area of donut = area of outer circle - area of inner circle

Need a Circle class, a Washer class, and an application class

Page 45: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-45

UML Class Diagram

composition relationship(an object of class Washer contains one or more objects of class Circle)

WasherAppl

main()readDouble()readInt()

JOptionPanefrom javax.swing

readDouble()readInt()…

Washer

computeRimArea()computeWeight()setInner()setOuter()setTickness()setDensity()toString()

inner: Circleouter: Circlethickness: doubledensity: double

Circle

setRadius()getRadius()computeArea()computeCircum()toString()

radius: doubleclass imported from javax.swing package

associationrelationship(a class calls the other’s methods)

Page 46: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-46

ANALYSIS, cont’d.

Data RequirementsProblem Inputs Problem Outputs

inner radius weight of batch of washersouter radiusthicknessdensityquantity

Relevant formulasarea of circle= ¶ x radius2

perimeter of circle = 2 x ¶ x radius area of donut = area of outer circle - area of inner circle

Page 47: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-47

DESIGN of Circle class

Circle classData fieldsdouble radius

Instance methodsdouble computeArea()double computeCircum()

Attributesthe circle radius

BehaviorComputes the circle area.Computes the circle

circumference.

Need a Circle class, a Washer class, and an application class

Page 48: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-48

Circle class

/* * Circle.java Author: Koffman and Wolz * A class that represents a circle */public class Circle {

private double radius;

public Circle() {}

public Circle(double rad) { radius = rad; }

public void setRadius(double rad) { radius = rad; }

public double getRadius() { return radius; }

Page 49: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-49

Circle class, cont’d.

public double computeArea() { return Math.PI * radius * radius; }

public double computeCircum() { return 2.0 * Math.PI * radius; }

public String toString() { return "circle with radius: " + radius; }}

Page 50: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-50

DESIGN of Washer Class

Data fieldsCircle innerCircle outerdouble thicknessdouble densityInstance methodsdouble computeRimArea()double computeWeightClasses used: Circle

Attributesthe inner circle the outer circlethe washer thicknessthe material densityBehaviorComputes the washer's rim area.Computes the washer's weight.

Algorithm for computeRimArea()1. Calculate the area of the outer circle and the area of the inner circle and return the difference.Algorithm for computeWeight()1. Multiply the rim area by the thickness and density.

Page 51: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-51

Washer Class

/* * Washer.java Author: Koffman and Wolz * A class that represents a washer */public class Washer { // data fields private Circle inner; private Circle outer; private double thickness; private double density; // methods public void setInner(double inRadius) { inner = new Circle(inRadius); } public void setOuter(double outRadius) { outer = new Circle(outRadius); } public void setThickness(double thick) { thickness = thick; }

Page 52: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-52

Washer Class, cont’d.

public void setDensity(double dens) { density = dens; } public double computeRimArea() { return outer.computeArea() - inner.computeArea();

} public double computeWeight() { return computeRimArea() * thickness * density; } public String toString() { return "inner circle, " + inner + "\nouter circle, " + outer + "\nthickness is " + thickness + ", density is " + density; } }

Page 53: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-53

WasherApp class

/* * WasherApp.java Author: Koffman and Wolz * A class that finds the weight of a batch of washers */import javax.swing.JOptionPane;

public class WasherApp {

// postcondition: returns a type double data value private static double readDouble(String prompt) { String numStr = JOptionPane.showInputDialog(prompt); return Double.parseDouble(numStr); }

// postcondition: returns a type int data value private static int readInt(String prompt) { String numStr = JOptionPane.showInputDialog(prompt); return Integer.parseInt(numStr); }

Page 54: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-54

WasherApp class, cont’d.

public static void main(String[] args) { // Create a Washer object Washer wash = new Washer();

// Get washer data & store it in the Washer object. wash.setInner(readDouble( "Enter inner diameter in centimeters") / 2); wash.setOuter(readDouble( "Enter outer diameter in centimeters") / 2); wash.setThickness(readDouble( "Enter thickness in centimeters")); wash.setDensity(readDouble( "Enter density in grams per cc"));

// Get the quantity of washers. int quantity = readInt("Enter quantity");

// Calculate the batch weight. double batchWeight = quantity * wash.computeWeight();

Page 55: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-55

WasherApp class, cont’d. and Sample Run

// Display washer information and batch weight. JOptionPane.showMessageDialog(null, wash.toString() + "\nThe weight of " + quantity + " washers is " + batchWeight + " grams"); }}

Page 56: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-56

Program Style: Separation of Concerns

• Each class was relatively easy to design and implement. By splitting the problem solution up into three classes, we were able to keep things simple.

• The Circle class focused on those tasks that were relevant to Circle objects

• The Washer class focused on those tasks that were relevant to Washer objects.

• Also, we now have two more reusable classes, Circle and Washer, which may turn out to be handy in other problem solutions.

Page 57: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-57

3.6 Class DecimalFormat • Placing the statement

import java.text.DecimalFormat;before a class definition imports class DecimalFormat.

• Inside the class definition, the statementDecimalFormat form = new DecimalFormat("0.##");creates a new DecimalFormat object form with pattern represented by the string "0.##". A number formatted using this pattern should have at least one digit before the decimal point and up to two digits after the decimal point. The fractional part of the number should be rounded to two digits.

• The statementSystem.out.println("The batch weight is " + form.format(batchWeight)); applies object form's format() method and returns a string representing the value of batchWeight formatted according to the pattern associated with object form (value is 2670.23). It displays the line:The batch weight is 2670.23 grams

Page 58: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-58

Class NumberFormat• Placing the statement

import java.text.NumberFormat; before a class definition imports class NumberFormat.

• Inside the class definition, the statementNumberFormat currency = NumberFormat.getCurrencyInstance();

creates a NumberFormat object currency for formatting currency amounts.

• The method call

currency.format(discountAmount)calls object currency's format() method and returns a string that represents the value of discountAmount in dollars. This string starts with a $ symbol and has two digits after the decimal point. If discountAmount is 34.5456, the method result is "$34.55" .

Question to ponder: Write a statement that displays the value of salary in currency format using object currency.

Page 59: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-59

3.7 Applets, AWT, and the Graphics Class

• You can draw lines and various geometric shapes (for example, rectangles, circles, ovals) with Java methods. You can specify the position of each line or shape and also its color.

• You must know the size of your drawing surface and how to reference the individual picture elements (called pixels) on it.

(0, 0) (499, 0)

(0, 299) (499, 299)

Drawing surface with 500 pixels horizontally

and 300 pixels vertically

Page 60: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-60

Java Abstract Window Toolkit (AWT)

• To do graphics programming, import the AWT package java.awt. The AWT contains a hierarchy of classes for displaying windows and GUI components. The Applet class has an associated drawing surface that can be accessed through its paint() method.

• An applet is intended to be a support object in a Web browser like Internet Explorer or Netscape. You can start up an applet from a browser, or you can use the program appletviewer which is part of Java.

• The appletviewer, processes a file with extension .html which contains a sequence of instructions in the HyperText Markup Language (HTML). In HTML, the line<applet code = Intersect.class width = 300 height = 300>

directs the appletviewer to load applet Intersect. File Intersect.class has the byte code for Intersect.java.

Page 61: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-61

File Intersect.html

<HTML><applet code = Intersect.class width = 300

height = 300></applet></HTML>

Page 62: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-62

File Intersect.java and Sample Run

/* * Intersect.java Author: Koffman and Wolz * An applet that draws intersecting lines */import java.awt.*;import java.applet.Applet;public class Intersect extends Applet { public void paint(Graphics g) { //Draw a black line from (0,0) // to (300, 200) g.setColor(Color.black); g.drawLine(0, 0, 300, 200); //Draw a blue line from (300, 0) // to (0, 200) g.setColor(Color.blue); g.drawLine(300, 0, 0, 200); //Write some text near bottom of applet. g.drawString("Black and blue intersecting lines", 75, 250); }}

(299, 299)

(75, 250)

Page 63: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-63

Methods in Graphics Class

Method CalldrawArc(x, y, w, h, a1, a2);

drawOval(x, y, w, h);

drawLine(x1, y1, x2, y2);drawRect(x, y, w, h);

drawString(s, x, y);

• Effect• Draws an arc inside the rectangle with

top-left corner at (x, y) and bottom-right corner at (x+w, y+h). The arc goes from angle a1 to angle (a1+a2), measured in degrees.

• Draws an oval inside the rectangle with top-left corner at (x, y) and bottom-right corner at (x+w, y+h)

• Draws a line with end points (x1, y1) and (x2, y2).

• Draws a rectangle with top-left corner at (x, y) and bottom-right corner at (x+w, y+h).

• Displays string s starting at (x, y).

Page 64: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-64

Methods in Graphics Class, cont’d.

Method CallfillOval(x, y, w, h);

fillArc(x, y, w, h, a1, a2);

fillRect(x, y, w, h);

paint(g);setColor(Color.red);

• Effect• Draws a colored circle inside the

rectangle with top-left corner at (x, y) and bottom-right corner at (x+w, y+h).

• Draws a colored pie slice inside the rectangle with top-left corner at (x, y) and bottom-right corner at (x+w, y+h). The slice goes from angle a1 to angle (a1+a2), measured in degrees.

• Draws a colored rectangle with top-left corner at (x, y) and bottom-right corner at (x+w, y+h).

• Draws a graphical image.• Sets the drawing color to red.

Page 65: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-65

Applet HappyFace

/* * HappyFace.java Author: Koffman and Wolz * An applet that draws a happy face */import java.awt.*;import javax.Applet.applet;

public class HappyFace extends Applet { // Data fields private int maxX = 500; private int maxY = 400; private int headX = maxX / 2; private int headY = maxY / 2; private int headRadius = maxY / 4; private int leftEyeX = headX - headRadius / 4; private int rightEyeX = headX + headRadius / 4; private int eyeY = headY - headRadius / 4; private int eyeRadius = headRadius / 10; private int noseX = headX; private int noseY = headY + headRadius / 4; private int noseRadius = eyeRadius; protected int smileRadius = (int) Math.round( 0.75 * headRadius);

Page 66: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-66

Applet HappyFace, cont’d.

// Methods public void paint(Graphics g) { g.setColor(Color.black);

// Draw head. g.drawOval(headX - headRadius, headY - headRadius, 2 * headRadius, 2 * headRadius);

// Draw left eye. g.drawOval(leftEyeX - eyeRadius, eyeY - eyeRadius, 2 * eyeRadius, 2 * eyeRadius);

// Draw right eye. g.drawOval(rightEyeX - eyeRadius, eyeY - eyeRadius, 2 * eyeRadius, 2 * eyeRadius);

// Draw nose. g.drawOval(noseX - noseRadius, noseY - noseRadius, 2 * noseRadius, 2 * noseRadius);

Page 67: Copyright  2003 Pearson Education, Inc. Slide 3-1 Chapter Outline 3.1A First Worker Class: Class FoodItem 3.2A Worker Class that Processes String Objects

Copyright © 2003 Pearson Education, Inc. Slide 3-67

Applet HappyFace, cont’d.

// Draw smile. g.drawArc(headX - smileRadius, headY - smileRadius, 2 * smileRadius, 2 * smileRadius, 210, 120); }}