Chapter 3:



Chapter 3 Object orientation |
|
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
- Open project chapter03\clock-display.
- 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.
- 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?
|
3.2 Abstraction and modulation
-
| Abstraction - Ignores details of object
implementation, concerned only with object
use. |
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();
total
+= balance; balance =
0; } |
3.4 Modularization in the clock example
From this brief analysis, we see the clock display has 2
number displays for hours and minutes.
3.5 Implementing the clock display
The clock display has 2 number displays for hours and
minutes. A number display needs two fields for the state of a
NumberDisplay object:
- value - the value of the number
- limit - the maximum of the value
public class
NumberDisplay { |
private int
limit; private int
value; |
| Constructor and
methods omitted |
|
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 { |
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
- Sketch the static Class diagram for the Exercise2A
class below.
- Show any dependency arrows.
- Sketch the dynamic Object diagram for the person
object below after execution of:
-
- Exercise2A person = new Exercise2A("John", "Crab");
- Show reference arrows.
- Sketch the Class diagram for the Exercise2B class below.
- Show any dependency arrows.
- Sketch the Object diagram for the couple object below after
execution of:
-
- Exercise2B couple = new Exercise2B();
- Show reference arrows.
|
public class
Exercise2A { |
private String name; private
String favoriteFood; |
public Exercise2A(String newName, String
food) { favoriteFood =
food; name =
newName; } |
|
public class
Exercise2B { |
private Exercise2A
husband; private Exercise2A
wife; |
public Exercise2B( )
{ husband = new
Exercise2A("John",
"Crab"); wife = new
Exercise2A("Sally",
"tripe"); } |
| |
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. |
| Truth tables - Define boolean
operations. |
- ! - not. Examples: !true is false, !false is
true.
-
| X |
!X |
| true |
false |
| false |
true |
-
- && - and. Result true when both
operands are true.
-
| A |
B |
A && B |
| false |
false |
false |
| false |
true |
false |
| true |
false |
false |
| true |
true |
true |
- || - or. Result true when either operand is
true
-
| A |
B |
A || B |
| false |
false |
false |
| false |
true |
true |
| true |
false |
true |
| true |
true |
true |
Exercise 3 - Logical
operators
- What is the result of the following?
- true && false
- false || true
- true && (false || true)
- !true || false
- (4 < 5)
- (4 < 5) && (6 >= 5)
- (4 > 5) || (6 <= 5)
|
NumberDisplay Source code
public class
NumberDisplay { |
private int
limit; private int
value; |
public
NumberDisplay(int
rollOverLimit) { limit =
rollOverLimit; value =
0; } |
public int
getValue() { return
value; } |
public String
getDisplayValue() {
if(value <
10)
return "0" + value;
else
return "" +
value; } |
public void
setValue(int
replacementValue) {
if((replacementValue >= 0) && (replacementValue <
limit))
value =
replacementValue; } |
public void
increment() { value =
(value + 1) %
limit; } |
|
Exercise 3 - Class NumberDisplay
Analysis
- Give the Java code to create a new
NumberDisplay object named miles with a
rollOverLiimit of 5.
- What is the state of miles?
- Give the Java code to set the object
miles to 5 using method setValue.
- Give the Java code to set the object
miles to 4 using method setValue.
- What is the new state of miles?
- Give the Java code to increment the object
miles one time.
- What is the new state of miles?
|
3.8.2 String Concatenation
| Concatenation operator - +
with one String operand results in a concatenated
String. |
- Examples:
- "abc" + "efg" is "abcefg"
- 1 + "a" is "1a"
- 1 + "2" is "12"
- 1 + "" is "1"
public String
getDisplayValue() {
if(value <
10)
return "0" + value;
else
return "" +
value; } |
|
Exercise 4 - getDisplayValue()
Analysis
- For value = 5, what is: "0" +
value
- For value = 5, what is: "" +
value
- Assume NumberDisplay object miles
has state:
limit = 10 value = 5
What is:
miles.getDisplayValue();
- Assume NumberDisplay object
miles has state:
limit = 120 value = 105
What is:
miles.getDisplayValue(); |
3.8.3 The modulo operator
| Modulo operator - % is the
remainder of division. |
| Division operator - / is the
quotient of
division. |
- Examples:
- 25 % 4 is 1
- 25 / 4 is 6
- 17 % 3 is 2
- ( 16 + 1 ) % 3 is 2
- 17 / 3 is 5
- (16 + 1 ) / 3 is 5
public void
increment() { value =
(value + 1) %
limit; } |
|
Exercise 5 - increment()
Analysis
- What are all the possible results of:
- What are all the possible results of:
- Assume NumberDisplay object miles
has state:
limit = 7 value = 5
What is:
miles.increment();
- Assume NumberDisplay object miles
has state:
limit = 7 value = 6
What is:
miles.increment();
- Rewrite value = (value + 1) % limit
using an if-statement.
|
3.8.4 Class ClockDisplay
public class
ClockDisplay { |
private NumberDisplay
hours; private NumberDisplay minutes; private
String
displayString; |
public
ClockDisplay() { hours =
new NumberDisplay(24); minutes = new
NumberDisplay(60);
updateDisplay(); } |
public
ClockDisplay(int hour, int
minute) { hours = new
NumberDisplay(24); minutes = new
NumberDisplay(60); setTime(hour,
minute); } |
public void
timeTick() {
minutes.increment();
if(minutes.getValue() == 0) {
hours.increment();
}
updateDisplay(); } |
public void
setTime(int hour, int
minute) {
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay(); } |
public String
getTime() { return
displayString; } |
private void
updateDisplay() {
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue(); } |
|
Exercise 6 - ClockDisplay
Analysis
In BlueJ
- Open project chapter03\clock-display.
- Create a ClockDisplay object that corresponds
to the object diagram at right.
- Inspect the object but don't close.
- Call each method.
- Create a ClockDisplay object with time at
23:58.
- Test that can be used to test that the clock
display rolls over hours and minutes correctly.
|
3.9 Objects creating objects
public class
NumberDisplay { |
private int
limit; private int
value; |
public
NumberDisplay( int rollOverLimit
) { limit =
rollOverLimit; value =
0; } |
| |
public class
ClockDisplay { |
private
NumberDisplay hours; private NumberDisplay
minutes; |
public
ClockDisplay() {
hours = new NumberDisplay( 24
); minutes = new
NumberDisplay( 60 );
updateDisplay(); } |
| |
Exercise 7 - Objects creating objects
In your head
- Match each of the Java code below with one of the objects created
at right.
- hours = new NumberDisplay( 24 );
- new ClockDisplay( );
- minutes = new NumberDisplay( 60 );
- Follow the Java code above as it executes:
public
ClockDisplay() {
hours = new NumberDisplay( 24
);
minutes = new NumberDisplay( 60 );
|
3.10 Multiple constructors
| Overloading - When more than
one constructor (or method) have the same name. The signature and call
are matched to determine which is
called. |
public class
ClockDisplay { |
private NumberDisplay
hours; private NumberDisplay minutes; private
String
displayString; |
public
ClockDisplay() { hours =
new NumberDisplay(24); minutes = new
NumberDisplay(60);
updateDisplay(); } |
public
ClockDisplay(int hour, int
minute) { 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(); } |
|
public class
NumberDisplay { |
private int
limit; private int
value; |
public
NumberDisplay(int
rollOverLimit) {
limit = rollOverLimit; value =
0; } |
public void
setValue(int
replacementValue) {
if((replacementValue >= 0)
&&
(replacementValue <
limit))
value =
replacementValue; } |
| |
| Exercise 8 - Multiple
constructors
Match the objects created below with the
corresponding Java code, the signature must match the call:
- ClockDisplay
myDisplay = ClockDisplay();
- ClockDisplay
myDisplay = ClockDisplay(15, 23 );
- ClockDisplay
myDisplay = ClockDisplay(24, 60);

|
3.11 Method calls
3.11.1 Internal method
calls
| Internal method call -
Calling a method defined within the class from a constructor
or method defined within the same class. The current object is
used. |
- Example:
- ClockDisplay
- Definition - public void setTime(int
hour, int minute)
- Internal Call - setTime(hour, minute);
3.11.2 External method calls
| External method call -
Calling a method defined within a different class. The dotted
object is used. |
- Example - ClockDisplay setTime method
calls the setValue method of hours and minutes, two
NumberDisplay objects.
public void setTime(int
hour, int minute) {
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay(); } |
public void setValue(int
replacementValue) {
if((replacementValue >= 0) && (replacementValue <
limit))
value =
replacementValue; } |
public class
ClockDisplay { |
private NumberDisplay
hours; private NumberDisplay minutes; private
String
displayString; |
public
ClockDisplay() { hours =
new NumberDisplay(24); minutes = new
NumberDisplay(60);
updateDisplay(); } |
public
ClockDisplay(int hour, int
minute) { hours = new
NumberDisplay(24); minutes = new
NumberDisplay(60); setTime(hour,
minute); } |
public void
timeTick() {
minutes.increment();
if(minutes.getValue() == 0) {
hours.increment();
}
updateDisplay(); } |
public void
setTime(int hour, int
minute) {
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay(); } |
private void
updateDisplay() {
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue(); } |
|
Exercise 8a - Internal and
External method calls
- Categorize the method calls of
ClockDisplay as internal or external.
- Example of an external method call:
hours.setValue(hour);
- Example of an internal method call:
updateDisplay( );
|
3.11.3 Summary of the clock display
Abstraction:
- ClockDisplay - Focus on display of NumberDisplay
objects hours (00-23) and minutes (00-59).
- NumberDisplay - Focus on representing, incrementing,
and getting the value of a modulus counter.
| Exercise 9
In BlueJ
- Change ClockDisplay (not NumberDisplay) to
display a 12 hour clock rather than a 24 hour clock.
- Modify the ClockDisplay constructors to a 12
hour NumberDisplay object.
- Modify updateDisplay method to display hour
12 when the object hours value is 0, hour 13 is 1, etc.
- Hints: Use hours.getValue() to get the
hours integer value. Use modulus operator (i.e. %).
- Test appropriately to verify that values of
object hours are displayed as 1-12 only.
|
3.11.4 Using a debugger
| Debugger - Tool for examining
a program state (variables and field values) and statements as it
executes. |
3.11.4.1 Setting breakpoints
-
| breakpoint - A flag that will
stop program execution during debugging.
|
Exercise 9.1 - Breakpoints
In BlueJ
- Create a ClockDisplay instance with
hour=13 and minute=58.
- Set a breakpoint in ClockDisplay method
timeTick.
- Open the editor for the ClockDisplay
class.
- Click on the line to breakpoint, the
statement: minutes.increment();
- In the BlueJ menu, click Tools | Set/Clear
Breakpoint.
- Call ClockDisplay method timeTick. The
debugger should highlight the first
breakpointed statement encountered in the program.
- What are the names of the instance
variables (or fields) of a ClockDisplay object. See the
Debugger window below.
- Double-click the minutes field to
inspect. What is the value?
- Close the inspection window.
|
3.11.4.2 Single stepping
-
| Single stepping - Executing a
single statement. |
| Exercise 9.2 - Single stepping
In BlueJ
- The minutes.increment(); should be
highlighted in the Debugger window.
- Click Step in Debugger to execute the
statement.
- What changed in the Debugger?
- Double-click the minutes field to
inspect. What changed?
- Click Step in Debugger to execute the
if-statement.
- Which statement was executed?
- Why?
Click Continue to complete the method
timeTick. |
| Exercise 9.3 - Single stepping
In BlueJ
- Call ClockDisplay method timeTick
again. The debugger should highlight the first breakpointed
statement encountered in the program.
- What is the statement at the breakpoint again?
- Double-click the minutes field to
inspect. What is the value?
- Close the inspection window.
- Click Step in Debugger to execute the
statement.
- Double-click the minutes field to
inspect. What is the value?
- Close the inspection window.
- Click Step in Debugger to execute the
if-statement.
- Which statement was executed?
- Why?
Click Continue to complete the method
timeTick. |
3.11.4.3 Stepping into methods
executes one statement but will not follow the execution of a
method.
executes one statement but follows the execution of a
method.
| Exercise 9.4 - Single stepping into
methods
In BlueJ
- Set a breakpoint at the first statement of
method setTime.
- Call method setTime with hour=23
and minute=59. The debugger should highlight the first
breakpointed statement encountered in the program.
- What local variables (or parameters) are
listed?
- Click Step to execute until the
statement below is highlighted:
- Click Step Into to execute into the
updateDisplay method.
- Click Step to follow the execution.
- Does the updateDisplay method return to
the point where it was called in timeTick?
|
3.12 Another example of object interaction
| Debugger - Tool for examining
a program state (variables and field values) and statements as it
executes. |
3.12.1 The mail system example
Exercise 10
- What are the static dependencies
shown by the class diagram?
In BlueJ
- Experiment with the mail-system project.
- Open the mail-system project.
- Create a MailServer object.
- Create two MailClient objects:
- name the two objects sophie and
juan.
- supply each the MailServer object
name just created
- give a user name that matches the object's
name (i.e. "Sophie" and "Juan").
- Use the MailClient objects to send and
receive messages using:
- sendMessage
- getNextMailItem or
printNextMailItem
- Sketch the object diagram from part 1 similar
to the ClockDisplay.
|
3.12.2 The this keyword
-
| this - The name of the object
used in an internal method. Needed when a name is overloaded
(same name used simultaneously in different ways).
|
The following MailTerm constructors behave identically. The first
constructor requires this because the field and parameter names are the
same in the scope of the MailItem constructor.
private String
from; private String to; private String
message; |
public MailItem(String
from, String to, String
message) { this.from
= from; this.to =
to; this.message =
message; } |
public MailItem(String
newFrom, String newTo, String
newMessage) { from =
newFrom; to =
newTo; message =
newMessage; } |
|
3.13 Using a debugger
3.13.1 Setting breakpoints
-
| breakpoint - A flag that will
stop program execution during debugging.
|
Exercise 11 - Breakpoints
In BlueJ
- Use sophie's sendMessage to send a
message from "Sophie" to "Juan".
- Don't read the message yet.
- Set a breakpoint in MailClient method
printNextMailItem.
- Open the editor for the MailClient
class and set a breakpoint at the first line of method
printNextMailItem.
- Click on the line to breakpoint.
- In the BlueJ menu, click Tools | Set/Clear
Breakpoint.
- Call MailClient method printNextMailItem
on juan. The debugger should highlight the first breakpointed
statement encountered in the program.
- What are the names of the instance
variables (or fields) of a MailClient object. See the
Debugger window below.

|
3.13.2 Single stepping
-
| Single stepping - Executing a
single statement. |
| Exercise 11 - Single stepping
In BlueJ
- Note there are no local variables listed
in the Debugger window.
- What does the statement do at the breakpoint?
-
- MailItem item =
server.getNextMailItem(user);
- Click Step in Debugger to execute the
statement.
- What changed in the Debugger?
- item is a local variable and references
the MailItem object for user "Juan".
- Since "Juan" has mail, which statement would
you expect the if-statement to execute next?
- Is the value of item listed as
null or something else?
- Click Step in Debugger to execute the
statement.
- Which statement was executed?
- Why?
Click Continue to complete the method
printNextMailItem. |
| Exercise 12 - Single stepping
In BlueJ
- Call MailClient method printNextMailItem
on juan. The debugger should highlight the first breakpointed
statement encountered in the program.
- Is the statement at the breakpoint again?
-
- MailItem item = server.getNextMailItem(user);
- Click Step in Debugger to execute the
statement.
- item is a local variable and references
the MailItem object for what user?
- Since "Juan" has mail, which statement would
you expect the if-statement to execute next?
- Is the value of item listed as
null?
- Click Step in Debugger to execute the
statement.
- Which statement was executed?
- Why?
Click Continue to complete the method
printNextMailItem. |
3.13.3 Stepping into methods
executes one statement but will not follow the execution of a
method.
executes one statement but follows the execution of a
method.
| Exercise 13 - Single stepping into methods
In BlueJ
- The breakpoint should still be set in method
printNextMailItem.
- Use sophie's sendMessage to send a
message from "Sophie" to "Juan".
- Don't read the message yet.
- Call MailClient method printNextMailItem
on juan. The debugger should highlight the first breakpointed
statement encountered in the program.
- What is the variable item?
- Click Step to execute until the
statement below is highlighted:
- Click Step Into to execute into the
print method.
- Continue to click Step Into to follow
the execution.
|
3.14 Method calling revisited
| Exercise 14 - Method calling revisited
In BlueJ
- Set a breakpoint in the first statement of
method sendMessage:
-
- MailItem mess = new MailItem(user, to,
message);
- Use sophie's sendMessage to send a
message from "Sophie" to "Juan".
- What are the formal parameters (i.e. local
variables) listed?
- Click Step to execute new
MailItem(user, to, message) method.
- What changed and why?
- Click Continue to complete the
execution.
- Use juan's sendMessage to send a message
from "Juan" to "Sophie".
|
3.15 Summary


Please send any comments to: jfdoyle@ius.edu
Copyright ©
2001-2004 by cgranda@ius.edu . All
rights reserved.