Chapter Complete
Chapter Complete
Chapter Complete
19574779 r ALL
Chapter 1 0
Objects and Classes
Search site
Overview
The basic concepts and terms of solving problems using a computer are covered,
including use of the BlueJ application and object oriented modeling of problems.
1.1 Objects and Classes
Problems solved on computers model some aspect of the real world. For
example, we calculate the date when the distance between Earth and Mars is a
minimum (August 27) by modeling the planetary orbits numerically. The line
between reality and computer modeling apparently grows less distinct when
money is earned and spent electronically or the plane we ride is often piloted by
a computer, but even in these cases the computer programmer has
implemented a model solution for the computer to follow.
Object-oriented programming is one approach to modeling problems based upon
how we humans naturally organize our environment - by classifying things with
similar attributes together. For example, on entering a room we unconsciously
classify individual objects in the room as desks, students, etc. We can then treat
desks as setting objects without thinking much about the details of an individual
desk.
•
Class - A class defines common fields (attributes) and methods
(actions) to objects.
• All objects classified as desks have height, color, location, etc. fields. The
desk class can be defined by its fields as:
class
Desk
height
color
location
•
Object - An object is one specific instance of a class where the
fields have a value.
A room may have 20 objects classified as desks, each desk has color, height,
location, etc. fields. Two desk objects, different instances of desk classification,
can then have field values of:
height 30 inches height 30 inches
color black color tan
location row 3, location row 4,
position 2 position 1
Page
1
Exercise 1
1. Name three classes of objects in your immediate possession at this
moment. Nothing risqué please!
2. Write each of the three class names and four obvious fields for each
class.
3. Pick one of the classes for which you possess several objects and define
values for each of the four fields.
Name object - Naming each desk allows us to distinguish one desk from
another by:
Desk desk1 = new Desk desk2 = new
Desk() Desk()
Exercise 2
• From Exercise 1, Question 3; Use Java to create and name two of
the objects.
BlueJ
The following assumes that textbook projects has been installed, if not, see
Getting Started.
• Open BlueJ
Page
2
Exercise 3 - Creating objects in BlueJ
•
Methods - A method performs action on the object by using the
Page
3
values of the fields.
Method makeVisible() sets the isVisible field to true.
1.4 Parameters
Two circles have been created with field values of:
circle_1 circle_2
diameter diameter
30 30
isVisible isVisible
false false
•
Parameters -
Parameters specify
values to be used by
methods.
The method call changeSize(50) specifies 50 as the parameter to the method.
Exercise 5 - Calling
methods with
parameters in
BlueJ
1. Right-click on circle_1 icon in BlueJ.
2. Choose makeVisible().
Page
4
7. Figure out how to call slowMoveVertical method.
•
Data type - Specifies the type of data value of a field
or parameter.
○ int - Integer (whole number). Examples: 34, -25, 9999999, 0.
○ double - real number. Examples: 14.76, 3963.4, 0.5.
○ boolean - Either true or false.
○ String - Anything enclosed in double quotes. Examples: "blue",
"12", "Hi there".
Exercise 6 - Calling methods with String
parameters
Page
5
can be called for the object.
Exercise 7 - Multiple
Instances
1. Create three Circle objects by right-clicking on
.
○ Make each visible.
○ Move each around.
○ Make each a different color.
2. Create two Triangle objects.
○ Make each visible.
○ Move each around.
○ Make each a different color.
1.7 State
•
State - The values for all fields of
an object.
The following field values completely define circle_1's state. If the state does not
change, the object does not change. Changing field diameter to 90 changes the
state of the object (and triples the diameter).
circle_1
int diameter
30
int xPosition
70
int yPosition
60
boolean isVisible
false
String color
"blue"
Page
6
○ Call changeColor method using a different color
parameter.
○ Note the color field value.
3. Inspect two objects of the same class (you should have two Circle
objects).
1. Are all fields the same?
2. Are all values the same?
Inspect a Triangle and Circle object simultaneously.
○ What fields are the same?
○ What fields are different?
Page
7
Exercise 9 - Using Objects
1. Create a house and sun similar to the
picture at right using the
shapes project classes Circle,
Triangle and Square.
2. Right-click on icon .
3. Click on Open Editor to see the source code text.
4. What is the name of the class?
○ Find the statement that defines the name of the class.
5. Find the fields for the sun and parts of the house.
○ What are the field names?
Page
8
6. Find the public void draw method.
○ What are the wall tasks?
○ Does the order in which the tasks are performed matter?
Java statements are written and read by humans but must be compiled
(translated from Java to computer code) before performed by computer.
•
Compile - Translating Java statements to computer
instructions.
Exercise 12 - Compiling
1. Open Editor to see the source code text.
2. Find the public void draw()
method.
○ Change the color of the sun to blue.
○ Compile by clicking the Compile button
(see figure at right).
○ What happened to picture_1 object?
○ Was picture_1 object using the most
recent definition of Picture class?
3. Create an instance of class Picture named
picture_1.
○ Call the draw method.
Exercise 13 - Editing
1. Open Editor to see the source code text.
2. Change the Picture class to have two suns.
a. Add another Sun field named sun2.
b. Compile by clicking the Compile button.
c. Create an instance of class Picture named picture_1.
d. Call the draw method.
3. Did two sun's appear? What happened?
4. Change the draw method appropriately for sun2.
a. Copy and paste sun source code.
i. Make necessary changes.
ii. Make sun2 a color different than sun.
iii. Position sun2 below sun.
b. Compile by clicking the Compile button.
c. Create an instance of class Picture named picture_1.
Page
9
Call the draw method.
Did two sun's appear? What happened?
Exercise 14 - Challenge
1. Open Editor to see the source code text.
2. Change the draw method to add a sunset of a sun.
○ Use the slowMoveVertical(int) method.
3. Compile by clicking the Compile button.
4. Create an instance of class Picture named picture_1.
○ Call the draw method.
Exercise 15 - Challenge
1. Open Editor to see the source code text.
2. Add a new method named sunset.
○ Use public void draw() as a pattern.
○ Move the slowMoveVertical call to the sunset method.
3. Compile by clicking the Compile button.
4. Create an instance of class Picture named picture_1.
○ Call the draw method.
Page
11
1. Continue Exercise 17.
2. Create a LabClass object with maximum of 5 students
○ The LabClass constructor signature indicates an int parameter
which must be passed the maximum number of students.
3. Call the numberOfStudents method.
○ What is the result?
The printList method prints the fields of a LabClass object to a terminal window.
Exercise 20 - Print LabClass object
1. Continue Exercise 19.
2. Call the printList method for the LabClass object.
○ What does printList the method do?
Exercise 21 - Exploring LabClass
1. Create a LabClass object.
○ The LabClass constructor signature indicates an int parameter
which must be passed the maximum number of students.
2. Create two Student objects with the following field values:
1. Lisa Simpson, student ID: 122044, credits: 56
2. Charlie Simpson, student ID: 12003P, credits: 6
LabClass method enrolStudent toenter the two Student objects.
○ Call the printList method for the LabClass object.
Top of Form
19574779 r ALL
Chapter 2
Search site
Understanding class definitions
powered by
FreeFind
C201\Projects\Chapter02\naive-ticket-machine
2. In BlueJ menu:
○ Click View
Page
13
○ Check Show Terminal.
3. In Terminal Window:
○ Click Options
○ Check Record method calls.
4. Create an instance of the class using TicketMachine(ticketCost)
constructor.
○ Supply an int parameter for the ticketCost in cents for $1.00.
5. Complete Exercise 2.1-2.4 on page 18 of the text.
Exercise 2.1
a. Try the getPrice method.
What does it do?
What is the return class?
b. Insert some money and check the balance using methods:
insertMoney
getBalance
c. Inspect the object.
d. Insert more money that a ticket costs.
e. Call method printTicket.
Exercise 2.2
○ Check the balance.
○ What is the balance after printTicket method is called?
○ Is that reasonable?
Exercise 2.3
○ Experiment by inserting different amounts of money before calling
printTicket method.
○ What is the balance after printTicket method is called?
○ What must happen to balance field in printTicket method?
Exercise 2.4
○ Experiment with the TicketMachine class before we examine in in
detail.
○ Create another TicketMachine object with a different ticket price.
○ Buy and print a ticket.
○ Does the ticket look much the same?
○ Is that reasonable behavior? Why?
Page
14
private int price;
private int balance;
private int total;
public TicketMachine(int ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
total += balance;
balance = 0;
}
}
2.3 Fields, constructors and methods
Exercise 2
1. What are the field names?
2. What is the constructor name?
3. What are the method names?
4. Where does TicketMachine class begin and end?
5. Give the beginning and ending of classes Picture, Circle, Student and
LabClass?
6. How do constructors and methods appear different?
Page
15
2.3.1 Fields
•
Fields - Store data for each
object.
Object constructed
by:
TicketMachine (43)
TicketMachine
Constructor
public TicketMachine(int
ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
price = ticketCost;
• Field price is assigned value of parameter ticketCost.
balance = 0;
• Field balance is assigned value 0.
Page
16
2.3.3 Passing data via parameters
•
Parameter - Pass value to constructors and
methods.
•
Formal parameter - Parameter name inside constructors
and methods.
public TicketMachine(int ticketCost) - Formal parameter is ticketCost.
•
Actual parameter - Parameter value outside constructors
and methods.
TicketMachine( 43 ) - Actual parameter is 43.
TicketMachine( 43
)
•
Scope - Limit of where a name is known. Formal parameters are only
known in constructor or method.
The scope (where known) of formal The scope of field balance is TicketMachine
parameter ticketCost is constructor, getBalance, insertMoney and
TicketMachine constructor. all other TicketMachine methods.
public TicketMachine(int public int
ticketCost) getBalance()
{ {
price = ticketCost; return balance;
balance = 0; }
total = 0;
}
public void insertMoney(int
amount)
Page
17
{
balance += amount;
}
2.5 Assignment
•
Assignment - Copies to the variable at the left-side of = from the value of
the expression at the right-side.
boolean
int balance; String name;
onFire;
balance = name =
onFire =
40*3; "Fred";
true;
For now, both sides must be the same data type: int, String, or boolean.
•
Expression - Computes
values.
int
String boolean
balance;
name; onFire;
Page
18
•
Methods - A method performs action on the object by using the
values of the fields.
Four methods of TicketMachine:
public int
getPrice()
{
return price;
}
public int
getBalance()
{
return balance;
}
total += balance;
balance = 0;
}
•
/**
* Return the price of a Comment
ticket.
*/ Header or
public int getPrice() signature
{
return price; Body
}
Page
19
•
Return type - int for getPrice which must return an int value such as 45
or price, void for insertMoney.
/**
* Receive amount of money in cents from a Comment
customer.
*/ Header or
public void insertMoney(int amount) signature
{
balance += amount; Body
}
•
Accessor Methods - Methods that return information such as getPrice
and getBalance.
Exercise 4 -Methods
1. How does the header of getPrice and insertMoney differ?
2. How does the body of getPrice and insertMoney differ?
3. Try in BlueJ.
○ Remove the return price; statement from getPrice.
○ Compile
○ What happened and why?
4. Write an accessor method getTotal that returns the total
field value.
○ Compile and test.
System.out.println("##############
####");
Page
20
System.out.println();
total += balance;
balance = 0;
}
Exercise 5 - Mutators
• In BlueJ:
○ Create a TicketMachine object with a positive ticket price.
○ Inspect the object doing the following calls:
1. Call insertMoney method on the object, inserting 53 cents.
2. Call insertMoney method on the object, inserting 47 cents. Is
insertMoney a mutator or accessor method?
3. Call printTicket method on the object. Is printTicket a mutator
or accessor method?
•
= Assignment only.
+= Add then
assignment.
Exercise 6 - Assignment
1. What is the value of balance after each
statement:
balance = 40;
balance = 20;
balance = 10;
System.out.println("##############
####");
System.out.println();
total += balance;
balance = 0;
}
•
Concatenation - Combining two Strings to one using the
+ operator.
a. "abc"+"def" is "abcdef"
b. "12"+3 is "123". The integer 3 is converted to a String "3" and then
"12" +"3" is concatenated.
Exercise 7 - Printing and String Concatenation
1. What is printed by the following?
System.out.println("# The BlueJ Line");
2. What is printed by the following when price is 54?
System.out.println("# " + price + " cents.");
3. What is the result of the following when price is 54?
a. "# " + price + " cents."
b. "ab" + "c"
c. 34 + 5
d. "34"+"5"
e. "34"+"5"
f. "# " +"price" + " cents."
g. "# + price + cents."
In BlueJ:
1. Create the TicketMachine object above.
○ Inspect the object.
○ Call the printTicket method on the object.
2. Exercise 2.19, page 33. Add a method prompt to the TicketMachine class.
The method has void return type and no parameters. The method body
should print:
Page
22
Please insert the correct amount of money.
3. Exercise 2.20, page 33. Add a method showPrice to the TicketMachine
class. The method has void return type and no parameters. The method
body should print:
The price of a ticket is xyz cents.
where xyz is replaced by the value of price field when the method is
called.
4. Exercise 2.22, page 33. Add a method showPrice to the TicketMachine
class. The method has void return type and no parameters. The method
body should print:
The price of a ticket is xyz cents.
Page
23
What do you know about return statements that explain why this version
is incorrect?
•
if else conditional - When condition is true, performs the first statement.
Page
24
When condition is false, performs statement following the else.
total += price;
balance -= price;
}
else {
System.out.println("You must insert at least: " + (price - balance)
+ " more cents.");
}
}
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
Exercise 12 - Local variables
In BlueJ:
1. Open the better-ticket-machine project.
Page
26
2. Create a TicketMachine object:
○ with a ticketPrice parameterof 25 cents.
3. Inspect the object.
○ Is amountToRefund variable a field of the object?
4. Call insertMoney method with amount parameter of 45 cents.
○ What happened to the object state?
5. Call refundBalance method.
○ What happened to the object state?
○ What value was returned?
6. Add the following line in method printTicket:
balance -= price;
amountToRefund = 0;
○ Compile. What does the error message mean?
System.out.println(count
);
}
Page
28
public void changeName(String
replacementName)
{
name = replacementName;
}
Page
29
1. "01234".length()
2. "Harvey".length()
3. name.length()
4. "01234".substring(1,4).length()
5. name.substring(0,5).length()
In BlueJ:
1. Open project C201\Projects\chapter01\lab-classes
○ Examine in the editor.
2. Student class contains how many:
○ fields
○ constructors
○ mutators
○ accessors
3. What do the accessor names have in common?
4. Exercise 2.40, page 44.
○ What would be returned by getLoginName for a student with the
name "Henry Moore" and the id "557214"?
5. Exercise 2.41, page 44.
○ Create a Student with name "djb" and id "859012". What happens
when getLoginName is called on this student? Why do you think this
is?
6. Exercise 2.42, page 44.
7. Exercise 2.43, page 44.
2.17 Summary
public class
Book
{
Page
30
In BlueJ:
1. Open project C201\Projects\chapter01\lab-
classes
○ Examine in the editor.
2. Exercise 2.45, page 47.
3. Exercise 2.46, page 47.
Top of F
19574779 r
0
Chapter 3
Object orientation
Search si
om of Form
Overview
Chapter 2 presented a first look at Java source code and details on fields,
constructors, parameters, methods, assignment and conditional statements.
Here we will examine fundamental problem solving approaches of
modularization and abstraction.
3.1 The clock example
A 24-hour clock displays time in hours:minutes format from 00:00
(midnight) to 23:59 (one minute before midnight).
Exercise 1 - Clock example
In BlueJ
1. Open project chapter03\clock-display.
2. Create a NumberDisplay object with rollOverLimit = 3.
○ Inspect the object but don't close.
○ Call increment() method at least 6 times.
○ What behavior does a NumberDisplay object exhibit.
3. Create a ClockDisplay object with hour=23 and minute = 58.
○ Inspect the object but don't close.
○ Call timeTick() method at least 3 times.
○ Notice the displayString field. What behavior does a ClockDisplay
object exhibit?
Page
31
Abstraction is the standard means humans use to handle complexity, we learn to
ignore it. Consider the chair on which you are setting. A chair implementation is
the modules:
• legs - 4 vertical metal bars about 20 inches long, 1 1/2 inch square,
painted black
• seat - 2 horizontal metal bars 20 inches in length and 2 horizontal
metal bars 18 inches in length
• padding - clothe covering foam rubber, about 24x18 inches,
originally light gray color
• etc.
We use the chair as an abstraction of these parts, ignoring the implementation
details to set on it. The details of the chair are important for understanding how
chairs are implemented but not needed to use a chair.
•
Modularization - Dividing an object into well-defined
components.
Modularization is somewhat the complement of abstraction. It is the standard
means humans use to divide complexity into smaller, simpler components.
Consider again the chair on which you are setting.
To implement a chair we first divide the chair abstraction into smaller modules,
for example the seat. We may then divide the seat into smaller modules, the
padding and seat. We can divide the padding into foam rubber and clothe
modules. Eventually we divide modules to its simplest level. We can then focus
on implementing each module separate of the others; the foam rubber module
can be made separate from the clothe module.
Modularization divides the whole into related detail groups; abstraction combines
the details into the whole.
3.3 Abstraction in software
You have already seen that seemingly simple software has considerable
complexity. Designing correct software is hard primarily due to the large number
of details that must each be correct. Abstraction allows us to think about details
as a group.
Recall the TicketMachine method printTicket, the details are listed below. We
abstract or ignore the details and think only that printTicket method prints a
ticket not about each println statement.
public void printTicket()
{
System.out.println("##############
####");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + "
cents.");
System.out.println("##############
####");
System.out.println();
Page
32
total += balance;
balance = 0;
}
3.4 Modularization in the clock example
}
The clock display has 2 number displays for hours and minutes. A clock display
needs two fields for the state of a ClockDisplay object:
• hours - the NumberDisplay for hours
• minutes - the NumberDisplay for minutes
public class
ClockDisplay
{
Page
33
private NumberDisplay
hours;
private NumberDisplay
minutes;
Constructor and methods
omitted
}
3.6 Class diagrams versus object diagrams
•
Class diagram - Shows the classes and
static relationships between them.
Static view - The class diagram at right shows
the class definition relationships. ClockDisplay
depends on the NumberDisplay.
•
Object diagram - Shows the objects and dynamic relationships
between them.
• Dynamic view - The object
diagram a right shows when the
program runs, the dynamic view.
• A ClockDisplay object and two
NumberDisplay objects have been
created.
• The arrow implies the ClockDisplay
hours object references the 11
NumberDisplay object.
• The ClockDisplay minutes object references the 03 NumberDisplay object.
Exercise 2 - Class diagrams and object diagrams
1. Sketch the static Class diagram for the Exercise2A class below.
○ Show any dependency arrows.
2. Sketch the dynamic Object diagram for the person object below after
execution of:
○
Exercise2A person = new Exercise2A("John", "Crab");
○ Show reference arrows.
3. Sketch the Class diagram for the Exercise2B class below.
○ Show any dependency arrows.
4. Sketch the Object diagram for the couple object below after execution of:
○
Exercise2B couple = new Exercise2B();
○ Show reference arrows.
Page
34
public class
public class
Exercise2B
Exercise2A
{
{
}
}
3.7 Primitive types and object types
•
Primitive type - Non-object
types.
○ int - Integer (whole number). Examples: 34, -25, 9999999, 0.
○ boolean - Either true or false.
○ char - One character enclosed in single quotes. Examples: 'a', '4'.
○ double - Real or floating pointing numbers. Examples: 123.0, 45.67
3.8 The ClockDisplay source code
3.8.1 Class NumberDisplay
Logic operators - Operate on boolean (true or false) to produce a
boolean result.
Page
35
fals tru
false
e e
tru fals
false
e e
tru tru
true
e e
•
• || - or. Result true when either operand is true
•
A ||
A B
B
fals fals fals
e e e
fals tru
true
e e
tru fals
true
e e
tru tru
true
e e
Page
36
}
public String
getDisplayValue()
{
if(value < 10)
return "0" + value;
else
return "" + value;
}
Page
38
○ n%4
○
2. What are all the possible results of:
○ n%m
○
3. Assume NumberDisplay object miles has state:
limit = 7
value = 5
What is: miles.increment();
4. Assume NumberDisplay object miles has state:
limit = 7
value = 6
What is: miles.increment();
1. Rewrite value = (value + 1) % limit using an if-
statement.
Page
40
limit = rollOverLimit; NumberDisplay( 24 );
value = 0; minutes = new
} NumberDisplay( 60 );
updateDisplay();
}
}
Page
41
hours = new
NumberDisplay(24);
minutes = new
NumberDisplay(60);
setTime(hour, minute);
}
public void setTime(int hour, int
minute)
{
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay();
}
Page
44
breakpoint - A flag that will stop program execution during
debugging.
Exercise 9.1 -
Breakpoints
In BlueJ
1. Create a
Page
45
•
Single stepping - Executing a single
statement.
executes one statement but will not follow the execution of a method.
Exercise 11 -
Breakpoints
In BlueJ
1. Use sophie's
sendMessage to
send a message
from "Sophie" to
"Juan".
2. Don't read the
message yet.
3. Set a breakpoint
in MailClient method printNextMailItem.
a. Open the editor for the MailClient class and set a breakpoint at the
first line of method printNextMailItem.
b. Click on the line to breakpoint.
Page
48
c. In the
BlueJ
menu,
click Tools
| Set/Clear
Breakpoint.
4. Call MailClient method printNextMailItem on juan. The debugger should
highlight the first breakpointed statement encountered in the program.
5. What are the names of the instance variables (or fields) of a MailClient
object. See the Debugger window below.
executes one statement but will not follow the execution of a method.
Page
50
In BlueJ
1. The breakpoint should still be set in method printNextMailItem.
2. Use sophie's sendMessage to send a message from "Sophie" to "Juan".
3. Don't read the message yet.
4. Call MailClient method printNextMailItem on juan. The debugger should
highlight the first breakpointed statement encountered in the program.
5. What is the variable item?
6. Click Step to execute until the statement below is highlighted:
○
○ item.print();
○
7. Click Step Into to execute into the print method.
8. Continue to click Step Into to follow the execution.
Page
51
Top of F
19574779 r
Chapter 4
Search si
Grouping Objects
FreeFind
Modified: 08/27/2004
Bottom o
Overview
Chapter 3 examined fundamental problem solving approaches of modularization
and abstraction. Here we will examine some of the ways objects may be grouped
together into collections.
4.1 Grouping objects in flexible-size collections
Many objects in life come in groups:
• drawer of socks
• list of people to invite to a wedding
• days in a month
• dozen eggs
Some groups are fixed in size while others are flexible size. We need
programming features for modeling both cases.
4.2 A personal notebook
• Stores notes
• No limit on number of notes
• Display individual notes
• Display number of notes stored
Exercise 1 - NoteBook class
In BlueJ
Page
52
1. Open project chapter04\notebook1.
2. Click View | Show Terminal
3. In Terminal window click Options | Record method calls
4. Create a NoteBook object.
○ Add two notes:
1. "Buy bread"
2. "Sell car"
○ Check the number of notes stored.
○ Show each note. The first note is numbered 0, the second 1,
etc.
private ArrayList
notes;
public NoteBook()
Page
53
{
notes = new
ArrayList();
}
Page
54
• ArrayList object notes after the following statements are executed:
1. private ArrayList notes;
2. notes = new ArrayList();
3. notes.add("Buy bread");
4.
notes.add("Sell car");
Exercise 2 - NoteBook methods
In BlueJ
1. Inspect the NoteBook object.
a. Click on the notes field and Inspect button.
What is the value of field size?
b. What do you think is the value of: notes.size()
c. Click on elementData and Inspect button.
What is the number of:
"Sell car"
"Buy bread"
2. Call method:
○ showNote to show note number 1.
○ numberOfNotes.
Store another note "11:30 mtg"
○ What is the number of this note?
○ What is the value of: notes.size()?
In what order does ArrayList objects store objects?
Update the object diagram at right by hand to include "11:30 mtg" note.
4.5
Numbering
within
collections
•
index - Position of an object in a
collection.
Page
55
Examples:
• Index 0 of notes ArrayList object is "Buy bread".
• Index 1 of notes ArrayList object is "Sell car".
Exercise 3 - Indexes
1. What would be the index of the next note
added?
2. What is:
○ notes.get(1);
○ notes.get(0);
○ notes.get(5);
○ System.out.println( notes.get( 1 ) );
int i = 0;
int i = 0;
i = i + 1;
while ( i <= 4 ) {
i = i + 1;
i = i + 1;
i = i + 1;
}
i = i + 1;
int i = 4;
int i = 4;
i = i - 1;
while ( i > 0 ) {
i = i - 1;
i = i - 1;
i = i - 1;
}
i = i - 1;
int i = 0;
i = i + 1;
System.out.println( i ); int i = 0;
i = i + 1; while ( i <= 4 ) {
System.out.println( i ); i = i + 1;
i = i + 1; System.out.println( i );
System.out.println( i ); }
i = i + 1;
System.out.println( i );
System.out.println( notes.get(0) int i = 0;
); while ( i <= 5 ) {
System.out.println( notes.get(1)
); System.out.println( notes.get( i )
System.out.println( notes.get(2) );
); i = i + 1;
System.out.println( notes.get(3) }
);
System.out.println( notes.get(4)
Page
57
);
System.out.println( notes.get(5)
);
if (notes.size() > 0)
System.out.println( 0 + ":" +
notes.get(0) );
if (notes.size() > 1) int i = 0;
System.out.println( 1 + ":" + while ( i < notes.size() ) {
notes.get(1) ); System.out.println( i + ":" +
if (notes.size() > 2) notes.get( i ) );
System.out.println( 2 + ":" + i = i + 1;
notes.get(2) ); }
if (notes.size() > 3)
System.out.println( 3 + ":" +
notes.get(3) );
Exercise 6 - listNotes
• Which of the above would be most
appropriate for the body of listNotes?
In BlueJ
1. Copy and paste the appropriate
signature and body for listNotes method
into NoteBook class.
○ Create an instance with 2 notes
and call the listNotes method.
2. Modify listNotes method to print the
notes in reverse order.
○ Create an instance with 2 notes
and call the listNotes method.
3. Modify deleteNote to print out an error
message if the note number parameter
is not valid.
Infinite loops
Looping is a powerful tool
but has the danger of
looping infinitely (i.e. the
loop never stops). A
simple example of an
infinite loop that prints
"Forever..." forever till
stopped externally is:
Page
58
while( true )
System.out.println( "Forever...");
• Stopping - In BlueJ an infinite loop can often be stopped by:
Page
59
System.out.println( notes.get( i ) );
System.out.println( i.next() );
i = i + 1;
}
}
•
System.out.println( theIter.next( ) );
2. From the diagram at right, what is printed
by:
Iterator it = notes.iterator();
System.out.println( it.hasNext( ) );
3. What is printed by:
Iterator it = notes.iterator();
System.out.println( it.next( ) );
System.out.println( it.next( ) );
System.out.println( it.next( ) );
System.out.println( it.hasNext( ) );
Page
60
The following classes define a Person with an age and name, and a Party class
that groups Person objects. The class definitions follow:
import java.util.ArrayList;
import java.util.Iterator;
Page
61
Party wedding = new Party();
wedding.arrive( p0 );
wedding.arrive( p1 );
4.9.3 Casting
A collection can hold any type of an object. It is therefore necessary to give the
compiler information as to the type of object retrieved from the collection by
casting the object to a specific type.
For example, in the above Party class, the guests ArrayList contains Person
objects. The following method call fails because the compiler does not know the
class of the object retrieved from the guests ArrayList:
(guests.get(1)).printPers
on();
The following method call succeeds because the compiler does know the class of
the object retrieved from the guests ArrayList:
((Person)
guests.get(1)).printPerson();
Generally, the object retrieved must be cast to the class of the method.
Exercise 7.2 - Casting
In BlueJ
1. Use the object diagram for Exercise 7.1, Question 5 above.
Page
62
○ Assignment - x[ index ] = y;
○ Copy - y = x[ index ];
Examples that produce the same result
int x0; int x[ ] = new int [ 3 ];
int x1;
int x2; x[ 0 ] = -3;
x[ 1 ] = -5;
x0 = -3; x[ 2 ] = -4;
x1 = -5;
x2 = -4;
String notes0 ;
String notes1 ; String notes[ ] = new String[3];
String notes2 ; notes[ 0 ] = "Buy bread";
notes[ 1 ] = "Sell car";
notes0 = "Buy bread"; notes[ 2 ] = "11:30 mtg";
notes1 = "Sell car";
notes2 = "11:30 mtg";
Page
63
while ( i < notes.size() ) { while ( i < notes.length ) {
System.out.println( notes.get( i ) ); System.out.println( notes[ i ] );
i = i + 1; i = i + 1;
} }
while ( i >= 0 ) {
System.out.println( i
+ notes[ i ] );
i = i - 1;
}
3. Define the object pages,
an array 4 ints, see the
figure at right.
4. Initialize index 2 of
pages to 15.
5. Give the statements to
print the figure at right.
int i = 0; int i = 0;
for ( i=0; i < notes.size() ; i++) { for ( i=0; i < notes.length; i++ ) {
System.out.println( notes.get( i ) ); System.out.println( notes[ i ] );
} }
Examples:
Page
66
• Print all the integers from 3 to 12
int i;
for ( i = 3; i <=12;
i++)
System.out.println( i
);
•
• Total all the hourCounts variables to sumHours:
int sumHours = 0;
for ( int i = 0; i < 24; i++)
sumHours = sumHours +
hourCounts[ i ];
System.out.println( hourCounts[
i ]);
• Find largest
value in array
hourCounts:
int largest;
largest = hourCounts[0];
for ( int i = 0; i < 24; i++)
if ( hourCounts[ i ] >
largest )
largest =
hourCounts[ i ];
Page
68
}
reader.printData();
}
}
public class
LogAnalyzer
{
Page
69
printHourlyCounts - Prints each of the 24 variables in the hourCounts array.
0:0
1:5
2:0
3:0
4:2
:
private tms[ ]
TicketMachine;
tms [ 2 ].insertMoney ( 70 );
tms [ 2 ].printTicket ( );
System.out.println( tms
[ 2 ].emptyMachine( ) );
return total;
}
In BlueJ
2. Add numberOfAccesses method to LogAnalyzer class and test.
Page
71
TicketMachine t0, t1, t2;
t0 = new
TicketMachine( 40 );
t1 = new
TicketMachine( 50 );
t2 = new
TicketMachine( 60 );
t0.insertMoney( 100 );
t1.insertMoney( 75 );
t2.insertMoney( 85 );
int sum = 0;
sum = sum +
t0.emptyMachine();
sum = sum +
t1.emptyMachine();
sum = sum +
t2.emptyMachine();
• Complete the following to obtain exactly the same results as above but
using a fixed size array and for-loop.
TicketMachine [ ] t;
t [ 0 ] = new
TicketMachine( 40 );
t [ 1 ] = new
TicketMachine( 50 );
t [ 2 ] = new
TicketMachine( 60 );
t [ 0 ].insertMoney( 100 );
t [ 1 ].insertMoney( 75 );
t [ 2 ].insertMoney( 85 );
int sum = 0;
Top of Form
19574779 r
ALL 0
Chapter 5
More Sophisticated Behavior
Search site
Bo
ttom of Form
Page
72
Overview
Chapter 4 examined some of the ways objects may be grouped together into
collections. Here we will look at several types of collections, random behavior,
and writing program documentation.
5.1 Documentation for library classes
The Java class library is extensive.
Documentation of the classes in HTML is
on the text CD for installation onto your
computer or is available by searching the
web.
5.2 The TechSupport system
• User enters question at keyboard
(we will see how to do user input).
• TechSupport system responds with
useful information. Version 1 has only 1 possible response.
private InputReader
reader;
private Responder
responder;
public SupportSystem()
{
reader = new
InputReader();
responder = new
Responder();
}
Page
73
while(!finished) {
String input = reader.getInput();
if(input.startsWith("bye")) {
finished = true;
}
else {
String response = responder.generateResponse();
System.out.println(response);
}
}
printGoodbye();
}
private void printWelcome()
{
System.out.println("Welcome to the DodgySoft Technical
Support System.");
System.out.println();
System.out.println("Please tell us about your problem.");
System.out.println("We will assist you with any problem you
might have.");
System.out.println("Please type 'bye' to exit our system.");
}
public class
Responder
{
public Responder()
{ }
public String generateResponse()
{
return "That sounds interesting. Tell me
more...";
}
}
String comparisions
• "Edward".startsWith("Ed") - True because "Edward" starts with
"Ed".
• "Edward".startsWith("rd") - False because "Edward" does not
starts with "rd".
Page
74
• input.startsWith("bye") - True when "bye" is at the beginning of
input String, otherwise false.
• "Edward".equals("Edward") - True.
• "Edward".equals("edward") - False.
while(!finished)
{}
printGoodbye();
}
2. What will the following Java statements do? When will printGoodbye() be
executed?
public void start()
{
boolean finished = false;
while(!finished)
{
String input =
reader.getInput();
if(input.startsWith("bye"))
{
finished = true;
}
}
printGoodbye();
}
In BlueJ
1. Type bye in the Terminal Window to stop execution from Exercise 1.
○ The start() method will not finish until bye is read.
○ If BlueJ seems to have gone on vacation, close BlueJ and Open the
project again.
2. Open class SupportSystem.
3. Place a breakpoint at the first executable statement of method start().
○ boolean finished = false;
4. Call the start() method.
○ Use Step to trace the execution of the method.
Page
75
5. What is your response when the following is executed?
○ String input = reader.getInput();
○ Type something into Terminal Window.
○ What is the value of input?
6. Use Step Into to execute completely:
○ String response = responder.generateResponse();
○ What is the value of response?
○ "AbC".toLowerCase is "abc"
○ " AbC ".toLowerCase().trim() is "abc"
○ input.trim().toLowerCase().startsWith("bye") trims the blanks,
converts to lowercase and tests that result starts with "bye".
Page
76
and uppercase characters entered for bye.
2. Test.
3. Can the improvement be written another way?
○ "AbC".equals("AbC") is true.
○ "AbC".equals("ABC") is false.
○ input.trim().toLowerCase().equals("bye") trims the blanks, converts
to lowercase and tests that result is equal "bye".
• == - Tests for equality of primitive types such as int, double, boolean,
char and whether the same object is referenced.
○ 4 == 3 is false.
○ 4 == 4 is true.
○ private TicketMachine t1;
private TicketMachine t2;
t1 = new TicketMachine(50);
t2 = t1;
t2 == t1?
In BlueJ
1. Change TechSupport method start() to finish when input is only bye using
the equals method.
2. Test.
private Random
generator;
public Dice()
{
generator = new
Random();
}
Exercise 6 - Random
In BlueJ
1. Create a new project named Exercise6.
2. Create a new class named Dice.
○ Open the Dice class.
○ Copy and paste the above class into the Dice class source
code.
3. Compile and test by calling the methods:
○ oneDie()
○ twoDie()
4. Do the results appear random?
Page
78
5. What does the following do?
○ generator.nextInt(6)+1
private Random
randomGenerator;
private ArrayList responses;
public Responder()
Page
79
{
randomGenerator = new
Random();
responses = new ArrayList();
fillResponses();
}
}
5.5 Packages and imports
• Packages contain libraries of Java classes not automatically part of the
Java language.
• importclass name makes the package of classes available in a program.
For example:
Page
80
• Dictionary associates the word as a key and the definition as the
value.
• Phone book associates the name as a key and the phone number as
the value.
ArrayList is not a map since only the object is stored at an index. Removing an
object can change the index of other objects, hence no fixed pairing is defined.
HashMap uses a key rather than an index. The key is mapped to an object.
Removing an object does not change the key-to-object mapping.
• put - The key
"one" is defined
to map to "I"
using put method
by:
HashMap englishToroman
= new HashMap();
englishToroman.put("one",
"I");
• get - The object
"one" is mapped
to "I" which is retrieved using get method by:
englishToroman.get("one
");
• The following translates English words for Strings "one" to "six" to
Roman "I" to "VI".
import
java.util.HashMap;
public class
EnglishToRoman
{
HashMap englishToroman;
public EnglishToRoman()
{
englishToroman = new
HashMap();
englishToroman.put("one",
"I");
englishToroman.put("two",
"II");
englishToroman.put("three",
"III");
englishToroman.put("four",
"IV");
englishToroman.put("five",
"V");
englishToroman.put("six",
Page
81
"VI");
}
Exercise 8 - Mappings
In your head
1. From the object diagram, are the HashMap keys in any obvious order?
2. What is the result of the following?
○ englishToroman.get("five");
○ englishToroman.get("four");
○ englishToroman.get("english");
3. Is (String) really necessary for:
○ return (String) englishToroman.get(english);
In BlueJ
1. Create a new project named Exercise8.
2. Create a new class named Mappings.
○ Open the Mappings class.
○ Copy and paste the above EnglishToRoman class into thesource
code.
○ Modify to map SSN (social security number) as Strings to peoples
names.
3. Compile:
○ Test by calling the methods to map SSN to a name.
○ Test by calling the methods to map name to a SSN.
○ What happened?
4. Add the same SSN twice to the mapping but with different names.
○ Test by calling the methods to map that SSN to a name.
○ What happened?
5. Use the Help in upper-right corner. A browser window should open to the
Sun Java website.
○ Find help on the HashMap class.
○ Find out how to check whether a given key is in a map.
Page
82
public class
Responder
{
}
TechSupport start() method modified to generate a response to specific words as
input.
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
String input = reader.getInput();
if(input.startsWith("bye")) {
finished = true;
}
Page
83
else {
String response =
responder.generateResponse(input);
System.out.println(response);
}
}
printGoodbye();
}
Exercise 9 - Maps
For the Terminal input of:
"crashes"
"crashs"
1. What is input:
○ String input = reader.getInput();
2. What is:
○ input.startsWith("bye")
○ responder.generateResponse(input);
/**
* This class implements an English number to Roman numerical
translation.
*
* @version 1.0
* @author Your Name
*/
Page
84
5. Regenerate the documentation.
Exercise 11 - Public/Private
In BlueJ
1. Open the TechSupport class.
○ Note private and public methods.
2. Create a TechSupport object.
○ Which of the methods can be called?
Exercise 12 - Public/Private
In your head
• In the TechSupport class.
○ Do you need to know that a Responder class object is one of the
fields?
○ When calling TechSupport methods, are you allowed to know about
fields or certain methods?
○ When calling TechSupport methods, are you allowed to know about
constructors?
Page
85
• private - methods that are private can only be accessed by other
methods of the same class. This hides the methods from external calls.
Methods not intended for external use should be private.
• public - Fields that are public can be
accessed and changed externally without
using mutator methods. The values of the
fields cannot be controlled, hence the
state of the object cannot be controlled.
5.12 Learning about classes from their
interfaces
•
interface - Describes what a class does
and how it is used without examining the
implementation.
We'll examine the class interfaces in the ball project to understand how to use
the classes without understanding how they are implemented.
Exercise 13 - Class interface
In BlueJ
1. Open the chapter05\balls project.
2. Create a BallDemo object.
○ Call drawdemo method.
○ Call bounce method.
3. In BlueJ menu:
○ Open Tools
○ Project Documentation
○ Regenerate
4. Read Canvas documentation and
from it:
○ Draw a circle.
○ Draw a rectangle.
Page
86
public class Test
{
private static int
count = 0;
private int i =
0;
public Test()
{
count = count + 1;
i = i + 1;
}
Exercise 14 - Constants
In BlueJ
1. Open a new project named static.
2. Create a new class named Test.
3. Copy and paste the above Test class
definition.
4. Create three Test objects.
○ Inspect two objects.
○ Show static fields.
○ What are the values of i and count?
5. Change:
private static int count = 0;
to
private static final int count = 0;
• Why the error?
Page
87
Top of Form
19574779 r
ALL 0
Chapter 6
Well-behaved Objects
Search site
Bottom of Form
Overview
Chapter 5 expanded the notion of collections to include maps. Important topics
discussed were information hiding and documentation. Static variables and
constants were also examined. Chapter 6 does not introduce new Java syntax
but important ideas about programming: testing small units, automating test,
regression testing, manual testing and debugging.
6.1 Testing and debugging
• testing small units
• automating test
• manual testing
• debugging
○ print statements
○ debugger
6.2 Unit testing within BlueJ
• Unit testing - Testing individual parts of an application ranging from a
class to individual methods.
• Application testing - Testing the complete application.
Exercise 1 - diary-prototype project
In BlueJ
1. Open project chapter06\diary-prototype
2. Select Day class.
○ Click Tools.
○ Project Documentation.
3. What are the stated values of the dayNumber parameter to the Day
constructor?
○ Would you expect it to work for those values?
○ What about other values?
4. Construct a Day object.
○ Are you testing a unit or the complete diary application?
5. Construct another Day objectusing dayNumber 367.
○ 367 exceeds the stated Day constructor boundary condition. Did
the constructor fail?
Page
88
○ Do you think something will eventually fail later?
○ Is it better to fail if the stated operating conditions are violated or
try to give some response?
○ What is another boundary condition?
public Exercise3Tests()
{ }
public void test()
{
Day day4 = new Day( 4 );
Appointment appt10 = new Appointment("Sleep
all day", 10);
day4.makeAppointment( 9, appt10 );
}
Page
90
Day class showAppointments() method.
○ Test whether two appointments can be scheduled at the same time.
3. Change one of the appointments to 6pm and call your test() method again.
○ Is this a positive or negative test?
4. In this case all positive tests return true to correctly indicate success.
Results can be combined using and (&&). All negative tests return false to
correctly indicate failure. How would we combine test results to indicate
the failure of a set of negative tests?
Page
91
• public void minus();
• public void equals();
• public void clear();
• public int getDisplayValue();
• public void numberPressed(int number);
Because the calculation engine is separate from the the user interface, it can be
implemented and fully tested independently of the user interface.
Exercise 5 - Modularization and
interfaces
In BlueJ
1. Open project chapter06\calculator-
engine
public int testPlus()
2. Create a CalcEngineTester object. {
○ Call the testAll() method. // Make sure the engine is in
a valid starting state.
○ Do you trust the printed results? engine.clear();
○ Call the testAll() method again. // Simulate the presses: 3 +
4=
○ Do you now trust the printed engine.numberPressed(3);
results? engine.plus();
engine.numberPressed(4);
3. The method at right tests the plus() engine.equals();
method. // Return the result, which
should be 7.
○ Change to test 32 + 4 =
return engine.getDisplayValue();
○ engine is a CalcEngine field of }
CalcEngineTester.
○ Call the testPlus() method at
least twice.
○ Do you trust the results?
Page
92
}
2. Do the comments seem sufficient to explain the class and method use?
Page
93
○ 9-4=
When minus() is called the second time the input so far to cause minus()
to be called has been: 9 -.
The state is now:
○ previousOperator = '-'
leftOperand = 0
displayValue = 9
All appears well. Now to start our manual walkthrough of the CalcEngine
class:
4. Line 3 calls applyPreviousOperator() and previousOperator = '-'.
5. Because previousOperator = '-' line 20 is executed and performs:
○ leftOperand -= displayValue
which is:
Page
94
5. displayValue = 0;
6. }
Page
95
11. displayValue = 0;
12. printState( "minus() exit" );
13. }
14.
15. private void printState( String where )
16. {
17. System.out.println(where+":
previousOperator="+previousOperator+
18. " displayValue="+displayValue+"
leftOperand="+leftOperand);
19. }
20.}
Page
96
9. printState( "minus() entry");
10. applyPreviousOperator();
11. previousOperator = '-';
12. displayValue = 0;
13. printState( "minus() exit" );
14. }
15.
16. private void printState( String where )
17. {
18. if ( debugging )
19. System.out.println(where+":
previousOperator="+previousOperator+
20. " displayValue="+displayValue+"
leftOperand="+leftOperand);
21. }
22.}
Page
97
Top of Form
19574779 r
ALL 0
Chapter 7
Designing Classes
Search site
B
ottom of Form
Overview
Chapter 6 covered important ideas about programming: testing small units,
automating test, regression testing, manual testing and debugging. Chapter 7
introduces the most creative part of programming: design.
7.1 Introduction
• bad design
○ difficult to implement
○ difficult to test
○ difficult to get to work correctly
○ difficult to change
7.2 The world-of-zuul game example
Exercise 1 - zuul-bad
In BlueJ
1. Open project
chapter07\zu
ul-bad
2. From the
class
diagram at
right, which
class should
you use to
play the
game?
3. Explore and
answer:
a. What
does the application do?
Page
98
b. What are the commands?
c. What does each command do?
d. How many rooms are there?
e. Draw a map of just the rooms connected to the outside Room using
the compass headings:
N
W E
S
Exercise 2 - zuul-bad
In BlueJ
1. From the class diagram above, open in the editor the class Room.
○ Change from Implementation to Interface.
○ According to your map, how were the outside Room exits defined?
•
coupling - A measure of the interconnectedness of classes. Classes that
are essentially independent of the internal operation of other classes are
loosely coupled. Communication between classes occurs only through well
defined interface (signature) methods. Loose coupling allows changing
how a class operates internally as long as the method interface remains
the same.
7.4 Code duplication
Exercise 3 - Code duplication
In BlueJ
1. The following Game methods have duplicated code.
○ Locate the duplication.
○ How can the duplication be eliminated?
○ Remove the duplication.
○ Test.
Page
99
private void goRoom(Command command)
{
if(!command.hasSecondWord()) {
System.out.println("Go where?");
return;
}
private void printWelcome()
{
String direction =
System.out.println();
command.getSecondWord();
System.out.println("Welcome
to Adventure!");
// Try to leave current room.
System.out.println("Adventure
Room nextRoom = null;
is a ....");
if(direction.equals("north"))
System.out.println("Type 'help'
nextRoom = currentRoom.northExit;
if you need help.");
if(direction.equals("east"))
System.out.println();
nextRoom = currentRoom.eastExit;
System.out.println("You are " +
if(direction.equals("south"))
nextRoom = currentRoom.southExit;
if(direction.equals("west"))
currentRoom.getDescription());
nextRoom = currentRoom.westExit;
System.out.print("Exits: ");
if(currentRoom.northExit !=
if (nextRoom == null)
null)
System.out.println("There is no door!");
System.out.print("north ");
else {
if(currentRoom.eastExit != null)
currentRoom = nextRoom;
System.out.print("east ");
System.out.println("You are " +
if(currentRoom.southExit !=
currentRoom.getDescription());
null)
System.out.print("Exits: ");
System.out.print("south ");
if(currentRoom.northExit != null)
if(currentRoom.westExit !=
System.out.print("north ");
null)
if(currentRoom.eastExit != null)
System.out.print("west ");
System.out.print("east ");
System.out.println();
if(currentRoom.southExit != null)
}
System.out.print("south ");
if(currentRoom.westExit != null)
System.out.print("west ");
System.out.println();
}
}
7.5 Making extensions
A good design should allow extensions to be readily made. Coherent, loosely
coupled classes are generally easier to extend than tightly coupled designs.
Consider your car's sound system. The system consists of several independent,
loosely coupled modules (speakers, antenna, radio/player). A speaker is coherent
because only speaker operations are part of the design . The speaker is loosely-
coupled because speakers interface to the player only through standard plug-in
connector and can easily be replaced.
Compare to an incoherent design where the turn-signals are are designed into
the speaker. A tightly coupled design might have the radio tuning in the speaker
system, changing speakers would require changing part of the radio system or
changing the speakers to accommodate the radio. Better to have speakers and
Page
100
radio independent systems that communicate through a well-defined interface,
the speaker connection.
7.5.1 The task
Add two new directions for room exits up and down.
7.5.2 Finding the relevant source code
The code defining and using room exits is in class Game methods
(printLocationInfo and goRoom)and in class Room.
Defining Room class fields public allows the Game class direct manipulation of
the fields, making the Room and Game class tightly coupled and difficult to
change independent of the other. We will break the tight coupling.
class Game class Room
{ {
private Room public Room
currentRoom; private void northExit;
goRoom(Command command) public Room
private void southExit;
printLocationInfo() { public Room
{ String direction = eastExit;
System.out.println("You command.getSecondWord(); public Room
are " + westExit;
Room nextRoom = null;
currentRoom.getDescription if(direction.equals("north")) public void
()); nextRoom = setExits(Room
System.out.print("Exits: "); currentRoom.northExit; north,
if(direction.equals("east"))
if(currentRoom.northExit nextRoom = Room east,
!= null) currentRoom.eastExit;
System.out.print("north if(direction.equals("south")) Room south,
"); nextRoom =
if(currentRoom.eastExit currentRoom.southExit; Room west)
!= null) if(direction.equals("west")) {
System.out.print("east nextRoom = if(north != null)
"); currentRoom.westExit; northExit =
north;
if(currentRoom.southExit if (nextRoom == null) if(east != null)
!= null) System.out.println("There eastExit =
System.out.print("south is no door!"); east;
"); else { if(south !=
currentRoom = nextRoom; null)
if(currentRoom.westExit ! printLocationInfo() southExit =
= null) } south;
System.out.print("west } if(west != null)
"); westExit =
System.out.println(); west;
} }
Page
101
○ Change field access from public to private.
○ The fields are now encapsulated within the Room class.
2. Compile Room and Game classes.
3. This tight coupling has been broken but must be fixed to allow adding
other directions.
7.6 Coupling
After breaking the tight coupling between Room and Game classes, the compiler
tells us where the coupling was broken because the northExit, etc. fields of Room
are no longer accessible. Without public access to Room fields we will define a
Room accessor getExit() method that returns the room at an exit in a given
direction. For example:
north east south west
outside.setExits(null, theatre, lab, pub);
outside.getExit("east");
returns the Room theatre.
Exercise 4.1 - Encapsulation and coupling
1. Assign using setExits Room lab with north exit to the
outside Room.
Page
102
changing the Room class. For example, any number of exits can be added by
calling setExit() repeatedly:
outside.setExits(null, theatre, lab, pub);
outside.setExit("east", theatre);
outside.setExit("south", lab);
outside.setExit("west", pub);
with the resulting object diagram at right.
Exercise 4.2 - Encapsulation and coupling
• Assign using setExit Room lab with north exit to the
outside Room.
// 1 // 2 // 3
if(direction.equals("south")
Page
103
return southExit;
if(direction.equals("west")
return westExit;
}
Exercise 5 - Decoupling
In BlueJay
1. Copy and paste the full version of the decoupled Room class // 3 below.
○ Compile Room and Game classes.
// 3
import java.util.HashMap;
class Room
{
private String description;
private String exitString;
private HashMap exits;
Page
104
2. Compiling Game class should give errors resulting from our decoupling
changes to Room. Setting exits of the outside Room is below:
○ outside.setExit("east", theatre);
○ outside.setExit("south", lab);
○ outside.setExit("west", pub);
3. Complete setting the theatre Room exits and comment out setting the
remaining Room exits for now.
○ Compile Game, more errors.
Exercise 6 - Decoupling
In BlueJ
1. Compile Game, more errors.
○ We have eliminated northExit, etc. in favor of the getExit()accessor
method of Room.
○ The following returns Room theatre for the Room at the "east" exit
of outside Room.
outside.setExit("east", theatre);
outside.setExit("south", lab);
outside.setExit("west", pub);
outside.getExit("east");
2. What are the changes to use getExit() rather than northExit in:
○ if(direction.equals("north"))
nextRoom = currentRoom.northExit;
Page
105
nextRoom =
currentRoom.westExit;
if (nextRoom == null)
System.out.println("There is no
door!");
else {
currentRoom = nextRoom;
printLocationInfo()
}
}
Exercise 7 - Decoupling
In BlueJ
1. Compile Game, more errors.
○ We have eliminated northExit, etc. which decouples but breaks the
printLocationInfo() method at:
if(currentRoom.northExit != null)
System.out.print("north ");
2. We need to maintain a list of exits for each Room. The following sets the
exits for the outside Room.
outside.setExit("east", theatre);
outside.setExit("south", lab);
outside.setExit("west", pub);
3. It is a simple matter to add a Room field named exitString that
accumulates by concatenating the direction String for each exit.
○ An accessor method getExitString() returns the String field
exitString.
○ For example:
outside.getExitString() returns "east south west".
4. What are the changes to use getExitString() rather than northExit in:
○ if(currentRoom.northExit != null)
System.out.print("north ");
Page
106
System.out.println("You are "
+
currentRoom.getDescription());
System.out.print("Exits: ");
if(currentRoom.northExit !
= null)
System.out.print("north ");
if(currentRoom.eastExit !
= null)
System.out.print("east ");
if(currentRoom.southExit !=
null)
System.out.print("south ");
if(currentRoom.westExit !
= null)
System.out.print("west ");
System.out.println();
}
7.7 Responsibility-driven design
•
responsibility-driven design - class design by assigning responsibilities
to each class, responsible for handling own data.
A class should handle its own data, as we saw with the northExit, eastExit etc.
making data accessible outside a class increases coupling.
7.7.1 Responsibilities and coupling
• Classes that are entirely responsible for their own internal data can
access the data in methods, taking advantage of insider knowledge
of how the data is arranged, represented, etc.
Page
107
Room data.
private void
printLocationInfo()
{
System.out.print("You are "
+
currentRoom.getDescription()
);
System.out.println("Exits: "
+
currentRoom.getExitString()); }
}
In BlueJ
1. The Room class would need an
accessor method at right to
return a full description of a Room
contents, exits, etc.
Page
108
validCommands[] =
{ "go", "quit", "help", "look" };
The same data is also in the
Game class printHelp() method:
class Game
{
private void printHelp()
{
System.out.println("You are
lost. You wander");
System.out.println("around
at the university.");
System.out.println();
System.out.println("Your
command words are:");
System.out.println(" go quit
help");
}
Implicit coupling - Adding more command words in CommandWords class
requires changing Game also.
We could add a CommandWords method to return a String of all the command
words and call it from printHelp(). But the class diagram indicates the Parser
class already depends on the CommandWords class, making Game depend on
CommandWords would increase coupling.
Good designs reduce coupling. Better to define a Parser method to return the
command words from the CommandWords class instead.
class CommandWords
{
class Game class Parser private static final String
{ { validCommands[] =
private Parser parser; private { "go", "quit", "help",
CommandWords "look" };
private void printHelp()
{ commands; public String getWords()
System.out.println( {
"You are lost."); public String String words = "";
System.out.println( getCommands() for(int i=0;
"Your command { i<validCommands.length; i+
words are:"); return +)
System.out.println( words = words + "
commands.getWords( "+
parser.getCommands()); );
} } validCommands[i];
return words;
}
Exercise 9
• Examine the following Game method. Does implicit coupling still exist with
CommandWords class?
Page
109
• What is needed to add the "look" command?
class Game
{
private boolean processCommand(Command
command)
{
boolean wantToQuit = false;
if(command.isUnknown()) {
System.out.println("I don't know what you
mean...");
return false;
}
String commandWord =
command.getCommandWord();
if (commandWord.equals("help"))
printHelp();
else if (commandWord.equals("go"))
goRoom(command);
else if (commandWord.equals("quit"))
wantToQuit = quit(command);
return wantToQuit;
}
currentRoom = outside;
System.out.println(currentRoom.getLongDescriptio
n());
}
System.out.println(currentRoom.getLongDescriptio
n());
}
}
}
7.12 Refactoring
refactoring - Adapting existing classes and methods to meet new requirements.
Often adds functionality at the expense of more complex classes or methods.
• Refactoring often results in additional fields and methods or dividing a
class that has grown less cohesive into several, more cohesive classes.
Page
112
Exercise 14 - Refactoring
Add items (money, monsters, etc.) of varying weights placed in rooms.
1. What data (fields) is needed for an item?
3. Where are the most obvious points for refactoring to have different items
in a room?
○ Will the Room class need refactoring?
○ Will Game class need refactoring?
○ Should a new Item class be defined with responsibility for the
items?
3. Should the Item class have responsibility that includes a player carrying an
item?
Page
113
player is carrying.
Page
114
Top of Form
19574779 r
ALL 0
Chapter 8
Improving structure with inheritance
Search site
Botto
m of Form
Overview
Chapter 7 introduced the design of classes. Chapter 8 examines a fundamental
object-oriented construct for reusing code: inheritance.
8 Introduction
•
inheritance - defines one class as an extension
on another.
•
• super (parent) class - The class that is extended with additional fields
and methods. TicketMachine is the super or parent class.
• sub (child) class - The class that inherits all fields and methods of the
super class. BusTicketMachine is the subclass of TicketMachine.
Page
115
2. { extends TicketMachine
3. private int price; 24.{
4. private int balance; 25. private String bus, stops;
5. private int total;
26. public BusTicketMachine( int
theCost, String theBus,
6. public TicketMachine(int String
ticketCost) theStops )
7. { 27. {
8. price = ticketCost; 28. super( theCost );
9. balance = 0; 29. bus = theBus;
10. total = 0; 30. stops = theStops;
11. } 31. }
Exercise 1 - Inheritance
• Suppose that we have created a BusTicketMachine by:
BusTicketMachine btm = new BusTicketMachine( 50, "Number 3", "4th St.
- Mall - Airport" );
Trace the execution of the constructors.
Page
116
8.1 The DoME example
Database of CD's and video's.
• The database will
store two
collections, one
for CD's and the
other for video's.
•
UML - Unified Modeling Language, a notation for designing and
understanding object oriented systems.
• CD and Video
Some of the data fields and
methods given in UML form that
are likely needed to model a
collection of CD's and video's.
The figure at right lists both the
fields (top) and methods
(bottom) for the CD and Video
class.
Note the common fields and
methods. We may determine
later that others may be
needed but this shows the
commonality between the two
classes.
We would like to avoid duplication, inheritance can be used when the child
classes are cohesive with the parent.
• Database objects
Page
117
The database holds the CD
and Video collections
separately as an ArrayList
object for each.
public Database()
{
cds = new ArrayList();
videos = new ArrayList();
}
Page
119
{ cds.add(theCD); }
public class CD
public class Video
{
{
public void print()
public void print()
{
{
System.out.print("CD: " + title +
System.out.print("video: " + title
" (" + playingTime +
+
" mins)");
" (" +
if(gotIt) {
playingTime + " mins)");
System.out.println("*");
if(gotIt) {
} else {
System.out.println("*");
System.out.println();
} else {
}
System.out.println();
System.out.println(" " + artist);
}
System.out.println(" tracks: " +
System.out.println(" " + director);
numberOfTracks);
System.out.println(" " +
System.out.println(" " + comment);
comment);
}
}
}
8.2 Using inheritance
•
inheritance - defines one class as an extension
on another.
○ The Item fields are private, are inherited but cannot be accessed
from the CD or Video class.
Page
121
Item class code
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
CD class code
Page
123
Video class code
Page
124
comment);
}
}
8.3 Inheritance hierarchies
Exercise 5 - Inheritance hierarchies
1. Extend the hierarchy diagram at right to
include jazz, blues, R&R, country western and
rap.
2. Extend the hierarchy diagram at right to
include musicals, science fiction, soap operas,
TV shows and comedy.
Item Video CD
public class Item public class Video public class CD extends
{ extends Item Item
private String title; { {
private int playingTime; private String director; private String artist;
private boolean gotIt; private int
private String comment; public void print() numberOfTracks;
public Item(String theTitle, {
int time) System.out.println(" " public void print()
+ director); {
public void } System.out.println(" "
setComment(String + artist);
comment) public String System.out.println("
getDirector() tracks: " +
public String getComment() { return director; }
numberOfTracks);
public void setOwn(boolean } }
ownIt)
public String getArtist()
public boolean getOwn() { return artist; }
Page
125
Exercise 6 - Inheritance and access rights
In BlueJ
1. Open project Chapter08/dome-v2
2. Create a CD object.
○ Call a public inherited method such as setComment().
3. Open class Video
4. Remove the extends Item
○ What is the result of compiling Video?
○ Why?
5. Restore the extends Item
Page
126
Exercise 7 - Inheritance and initialization
In your head
1. Trace the execution of:
○ CD mycd = new CD("Quacker",
"Duck", 300, 10000);
2. Trace the execution of:
○ Video myvideo = new
Video("Revenge of the Ducks", "A.
Duck", 9000);
In BlueJ
1. Open CD class and set a breakpoint at
first line of CD class constructor.
2. Create a CD object.
○ Inspect.
○ Step Into to step through the
execution.
○ What constructor was executed for
super()?
○ Are Item fields part of the CD
object in the Inspector?
One Two Three
1. public 13.public 26.public class Three extends Two
class class Two 27.{
One extends
One 28. private String threeS;
2. {
3. private 14.{
29. public Three(String theS)
String 15. private
oneS; String 30. {
twoS; 31. super("blue");
4. public 32. threeS = theS;
One(Stri 16. public
33. }
ng theS) Two(Strin
5. { g theS)
34. public String getThreeS()
6. oneS 17. {
35. {
= theS; 18.
super("r 36. return threeS;
7. }
ed"); 37. }
8. public 19. twoS 38.}
String = theS;
getOneS( 20. }
)
Page
127
21. public
String
9. { getTwoS(
)
10.
return 22. {
oneS; 23.
11. } return
twoS;
12.}
24. }
25.}
Exercise 8 - Reuse
In BlueJ
Page
128
1. Add the following constructor with no parameters to Item:
○ public Item () { }
2. Create a class Game that inherits from Item.
○ Game class has no fields, constructors or methods.
3. Create a class VideoGame that inherits from Game.
○ VideoGame class has no fields, constructors or methods.
4. Examine the class diagram.
○ What class or classes are inherited by VideoGame?
Incompatible
Compatible Types
Types
Page
131
VideoGame vg2 = new
Game();
Game();
Game game2 = new
Game game2 = new
VideoGame();
Item();
•
Variables and subtypes
-Variables reference objects of
their type or subtype. Cannot
reference (i.e. be assigned)
supertype objects.
•
•
Substitution -Subtype objects
can be substituted wherever
supertype object allowed.
Page
132
One Two Three
16.public
class
Three
1. public extends
class Two
One
8. public class Two extends One 17.{
2. {
9. { 18. private
3. private String
String 10. private String twoS;
threeS;
oneS;
11. public Two(String theS)
19. public
4. public 12. { Three(Stri
One(Stri ng theS)
ng theS) 13. super("red");
14. twoS = theS; 20. {
5. {
15. } 21.
6. oneS super("bl
= theS; ue");
7. } 22. threeS
= theS;
23. }
Compatible Incompatible
db.addItem( item1 );
db.addItem( game1 ) db.addGame( item1 );
; db.addVideoGame( ite
db.addItem( vd1 ); m1 );
db.addGame( vd1 ); db.addVideoGame( ga
db.addVideoGame( v me1 );
d1 );
•
Passing subtypes -Actual parameters can be passed to formal
parameters of the same or supertype.
•
•
Passing supertypes -Actual parameters cannot be passed to formal
parameters of a subtype.
Page
134
3. db.addGame(vg1);
4. db.addVideoGame(item1);
5. db.addVideoGame(vg1);
6. db.addVideoGame(game1);
Page
135
21. public String
getS() 34. public String getS()
getS()
9. { 35. {
22. {
10. return oneS; 36. return threeS;
23. return twoS;
11. } 37. }
24. }
12.} 38.}
25.}
System.out.print( myOne.getS() )
• Database list method can handle any objects of type or subtype Item.
• Item, CD and Video have separate print() methods.
• item.print() polymorphic because the type of item can be Item, CD or
Video.
• Item class print() called.
Page
136
System.out.println(); // empty line
between items
}
Exercise 12 - Object
Are the following equivalent according to the
hierarchy at right?
public class Game extends
Object
public class Game extends
Item
Which are valid?
public class Database
{
public void addObject( Object
theObject )
public void addItem( Item theItem
)
Database db = new Database();
Object object1 = new Object();
Item item1 = new Item();
1. item1 = object1;
2. object1 = item1;
3. db.addObject( item1 );
4. db.addObject( object1 );
5. db.addItem( item1 );
6. db.addItem( object1 );
Page
139
CD cd1 =
aL.get( 0 ); // 1.
Compile error, CD = Object
Video vd1 = (Video)
aL.get( 1 ); // 2. Compile OK
CD cd2 = (CD)
aL.get( 1 ); // 3. Compile
OK but runtime error!
CD = Video.
• Which of the
following give a
runtime error?
a. aOne =
(One)
aL.get(0);
b. aThree =
(Three)
aL.get(2);
c. aThree =
(Three)
Page
140
aL.get(1);
d. aTwo =
(Two)
aL.get(2);
e. ((Three)
aL.get(2)
).getS();
Page
141
ArrayList aL = new ArrayList();
Integer integer1 = new
Integer( 5 );
aL.add( integer1 );
aL.add( new Integer( 3 ) );
Exercise 13 - Wrappers
• What is the value of int1 and
int2?
Top of Form
19574779 r ALL
Chapter 9
Search site
More about inheritance
power
FreeFind
Overview
Page
142
Chapter 8 introduced inheritance. Chapter 9 discusses key elements of
inheritance - method overriding and polymorphism.
•
Polymorphic -Many
shapes.
•
•
Polymorphic method-When inherited methods are over-ridden, the type
the object references determines the method executed.
•
Variables and subtypes -Variables reference objects of their type or
subtype. Cannot reference (i.e. be assigned) supertype objects.
•
•
Substitution -Subtype objects can be substituted wherever supertype
object allowed.
overriding - A subclass method of the same name as a super class method will
be called for the subclass object. The sub class method has precedence over the
super class method.
Method Polymorphism - When a method is overridden (i.e. methods with the
same name in an inheritance hierarchy), the object's class determines which of
the methods is called.
• Method printTicket() is defined in both classes above, a TicketMachine
object will invoke the TicketMachine printTicket() method, a
BusTicketMachine object will invoke the BusTicketMachine printTicket()
method.
Page
143
8. price = ticketCost;
28. super( theCost );
9. balance = 0;
29. bus = theBus;
10. total = 0;
30. stops = theStops;
11. }
31. }
Page
144
13.public class Two
1. public class One 26.public class Three
extends One
extends Two
2. { 14.{
27.{
3. private String 15. private String
oneS; 28. private String
twoS;
threeS;
4. public 16. public Two(String
One(String 29. public Three(String
theS)
theS) theS)
17. {
5. { 30. {
18. super("red");
6. oneS = theS; 31. super("blue");
19. twoS = theS;
7. } 32. threeS = theS;
20. }
33. }
8. public String
getS() 21. public String
34. public String getS()
getS()
9. { 35. {
22. {
10. return oneS; 36. return threeS;
23. return twoS;
11. } 37. }
24. }
12.} 38.}
25.}
Exercise 0b - Polymorphism
• What is the hierarchy?
• Trace the execution.
One myOne = new
Two("red");
Two myTwo = new
Three("white");
Three myThree = new
Three("blue");
System.out.print( myOne.getS() )
;
System.out.print( myTwo.getS() )
;
System.out.print( myThree.getS(
) );
9 Introduction
You may have noticed that the second DoME
example that used inheritance did not print all the
data fields of CD and Video. Only the fields of Item
class were printed. The reason being that the Item
method print() only has access to Item fields.
Page
145
Database list() method calls:
Item item = (Item) iter.next();
item.print();
Item Video CD
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
public void print() public class CD
{ public class Video extends Item
System.out.print("title: " + extends Item {
title + { private String artist;
" (" + playingTime + private String director; private int
" mins)"); : numberOfTracks;
if(gotIt) { : :
System.out.println("*"); :
} else {
System.out.println();
}
System.out.println(" " +
comment);
}
Page
146
• Add print() methods for CD and Video classes.
○ Copy and paste print() from below.
• Create a Video, CD and Database object.
○ Use Database method addItem() to add the CD
and Video object to the database.
• Call the Database method list() to print the database.
○ Did the Item method print() execute?
Item Video CD
public class Item
{
private String title;
private int public class CD
playingTime; extends Item
private boolean {
gotIt; private String
private String artist;
comment; public class Video extends Item private int
numberOfTracks;
public void print() {
{ private String director;
Page
147
• CD and
Video call
Item
method
print().
We'll see
how
shortly.
9.2.1 Calling print from Database
Database list() method calls:
public void list()
{
for(Iterator iter = items.iterator(); iter.hasNext(); )
{
Item item = (Item) iter.next(); // item is CD or Video
item.print(); // Call CD or Video print()
method
}
}
static type - The type a variable is declared in the Java source code. Used for
type checking at compile time.
Page
148
{
System.out.print("title: "
+ title + public void print()
" (" + playingTime { {
+ " mins)"); System.out.println("CD
if(gotIt) { System.out.println("Vide " + artist);
o"+ System.out.println("
System.out.println("*"); director); tracks: " +
} else { }
System.out.println(); : numberOfTracks);
} : }
System.out.println(" " + :
comment); :
}
v1.print();
1. v1 accessed.
2. v1 found to be a Video object.
3. Video class has a print() method.
4. Video print() executed. Item print() blocked.
v1.print();
1. v1 accessed.
2. v1 found to be a Video object.
3. Video class has a print() method.
4. Video print() executed. Item print()
blocked.
9.5 Super call in methods
In the following, the print() methods of CD and
Video override the print() method of Item for CD
and Item objects.
To call the print() method of Item for CD and
Item objects, the print() methods call super
class print() method, Item.
Page
149
No changes to super class method.
Item Video CD
public class Item public class CD extends
{ Item
private String title; public class Video {
private int playingTime; extends Item private String artist;
private boolean gotIt; { private int
private String comment; private String director; numberOfTracks;
public void print()
{
System.out.print("title: " public void print() public void print()
+ title + { {
" (" + playingTime super.print(); super.print();
+ " mins)"); System.out.println("CD
if(gotIt) { System.out.println("Vide " + artist);
System.out.println("*"); o"+ System.out.println("
} else { director); tracks: " +
System.out.println(); }
} numberOfTracks);
: }
System.out.println(" " + :
comment); :
} :
Page
150