Chapter 2:



Chapter 2 Understanding class definitions
|
|
Overview
Chapter 1 presented the general concepts behind object
oriented programming and the skills needed for creating and using objects from
predefined classes. Here we will define and refine these concepts more
precisely and more detailed. We will also examine how to take different
actions dependent upon a condition being true or
false.
2.1 Ticket machines
Train station ticket machines print a ticket when the
correct money is inserted. We define a class that models a naive ticket
machine where:
- a machine is constructed to print tickets of one set
amount
- customers get the ticket price
- customers insert money
- customers check balance
- customers request ticket to be printed
| Exercise 1
In BlueJ
- Open project:
C201\Projects\Chapter02\naive-ticket-machine
- In BlueJ menu:
- Click View
- Check Show Terminal.
- In Terminal Window:
- Click Options
- Check Record method calls.
- Create an instance of the class using
TicketMachine(ticketCost) constructor.
- Supply an int parameter for the ticketCost in
cents for $1.00.
- Complete Exercise 2.1-2.4 on page 18 of the
text.
Exercise 2.1
- Try the getPrice method.
- What does it do?
- What is the return class?
- Insert some money and check the balance using
methods:
- Inspect the object.
- Insert more money that a ticket costs.
- 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?
|
2.2 Examining a class
definition
The TicketMachine class definition source code of
page 20 with comments removed.
public class
TicketMachine { |
private int
price; private int balance; private int
total; |
public
TicketMachine(int
ticketCost) {
price = ticketCost;
balance = 0; total =
0; } |
public int
getPrice() {
return
price; } |
public int
getBalance() {
return
balance; } |
public void
insertMoney(int
amount) {
balance +=
amount; } |
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; } |
|
2.3 Fields, constructors and
methods
Exercise 2
- What are the field names?
- What is the constructor name?
- What are the method names?
- Where does TicketMachine class begin and
end?
- Give the beginning and ending of classes
Picture, Circle, Student and LabClass?
- How do constructors and methods appear
different?
|
2.3.1 Fields
-
| Fields - Store data for each
object. |
|
Field definitions
private int
price; private int balance; private int
total; | |
Object named ticketMachine_1, an
instance of TicketMachine class. It corresponds to the field
definitions.

|
- private - More in Chapter 5, for now always use
private.
- int - The value of the field must be a whole
number, an integer.
2.3.2 Constructors
-
| Constructors - Create an
instance of the class (object) and initialize the fields to a known
state. |
|
TicketMachine
Constructor
public TicketMachine(int
ticketCost) {
price = ticketCost;
balance = 0; total =
0; } | |
Object constructed by:
TicketMachine
(43)

|
price = ticketCost;
- Field price is assigned value of parameter
ticketCost.
balance = 0;
- Field balance is assigned value 0.
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.
Passing actual parameter 43 to
formal parameter ticketCost.
public TicketMachine( int
ticketCost)
TicketMachine ticketMachine_1 = new
TicketMachine( 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
parameter ticketCost is TicketMachine constructor.
public TicketMachine(int
ticketCost) {
price = ticketCost;
balance = 0; total =
0; } | |
|
The scope of field balance is
TicketMachine constructor, getBalance, insertMoney and all
other TicketMachine methods.
public int
getBalance() {
return balance; } |
public void
insertMoney(int
amount) { balance
+=
amount; } | |
Exercise 3 - Formal Parameters,
Fields and Scope
public int
getPrice() {
return price; } | |
private int
price; private int balance; private int
total; | |
- What is the formal parameter of
insertMoney method?
- What is the formal parameter of getPrice
method?
- What is the scope of amount?
- Can balance be used in method
getPrice?
- Can amount be used in method
getPrice?
- Try in BlueJ.
- In method getPrice change return
price; to return amount;
- Compile.
- What happened and
why?
|
2.5 Assignment
-
| Assignment - Copies to the
variable at the left-side of = from the value of the expression at the
right-side. |
int
balance; balance =
40*3;
|
String name; name =
"Fred";
|
boolean onFire; onFire =
true; |
For now, both sides must be the same data type: int,
String, or boolean.
-
| Expression - Computes values.
|
Exercise 3.5 - Assignment and
Expressions
| int
balance;
|
String
name;
|
boolean
onFire; |
What is the value of the following?
- balance = 40*3+2;
- name = "Fred" + "Flintstone";
- onFire = true or false;
|
2.6 Accessor methods
-
| 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; } |
public void
insertMoney(int
amount) {
balance +=
amount; } |
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; } | |
-
- Comment - For humans to read. Starts
with /* and ends with */
- Header - Defines method name, return
data type, and formal parameters.
- Body - Specifies what the method does in
form of variable definitions and statements. Starts with { and ends
with }.
|
/** * Return
the price of a ticket. */ public int
getPrice() {
return price; } |
Comment
Header or signature
Body | |
-
| 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
customer. */ public void insertMoney(int
amount)
{ balance +=
amount; } |
Comment
Header or signature
Body | |
-
| Accessor Methods - Methods
that return information such as getPrice and
getBalance. |
Exercise 4 -Methods
- How does the header of getPrice and
insertMoney differ?
- How does the body of getPrice and
insertMoney differ?
- Try in BlueJ.
- Remove the return price; statement
from getPrice.
- Compile
- What happened and why?
- Write an accessor method getTotal that
returns the total field value.
|
2.7 Mutator methods
-
| Mutator methods - Change the
values of the object's fields. |
Assignment changes a variable, such as a field. Calling
method printTicket mutates the field balance =
0;
| |
public void
insertMoney(int amount)
{ balance +=
amount; } | |
|
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; } | |
Exercise 5 -
Mutators
- In BlueJ:
- Create a TicketMachine object with a positive
ticket price.
- Inspect the object doing the following calls:
- Call insertMoney method on the
object, inserting 53 cents.
- Call insertMoney method on the
object, inserting 47 cents. Is insertMoney a mutator or
accessor method?
- Call printTicket method on the
object. Is printTicket a mutator or accessor method?
|
-
| = Assignment only.
+= Add then
assignment. |
Exercise 6 -
Assignment
- What is the value of balance after each
statement:
balance = 40; balance = 20; balance =
10;
- What is the value of balance after each
statement:
balance = 40; balance = balance +
20; balance = balance + 10;
- What is the value of balance after each
statement:
balance = 40; balance += 20; balance +=
10;
|
2.8 Printing from methods
-
| System.out.println( expression
) - Prints the value of the expression followed by a new line to
BlueJ Terminal Window. |
Printing object ticketMachine_1
| |
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; } | |
|
|
################## # The BlueJ Line #
Ticket # 43
cents. ################## |
|
-
| Concatenation - Combining two
Strings to one using the + operator.
|
- "abc"+"def" is "abcdef"
- "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
- What is printed by the following?
System.out.println("# The BlueJ
Line");
- What is printed by the following when
price is 54?
System.out.println("# " + price + "
cents.");
- What is the result of the following when
price is 54?
- "# " + price + " cents."
- "ab" + "c"
- 34 + 5
- "34"+"5"
- "34"+"5"
- "# " +"price" + " cents."
- "# + price + cents."
In BlueJ:
- Create the TicketMachine object above.
- Inspect the object.
- Call the printTicket method on the
object.
- 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:
Please insert the correct amount of
money.
- 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.
- 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. |
2.9 Summary of the naive ticket
machine
| Exercise 8 - TicketMachine
In BlueJ
- Implement another TicketMachine constructor:
- with no ticketPrice parameter
- price is fixed at 1000 cents
- create a TicketMachine object using your new
constructor
- create a TicketMachine object using the old
constructor and an actual parameter for a ticket price of 54 cents.
- Inspect both objects. You should have
two inspector windows. Is there any difference in the two objects?
- Call insertMoney method using both
objects.
- Call printTicket method using both
objects. Is there any difference in the two objects?
In your head
- Exercise 2.26, page 34.
Why does the following version of
refundBalance not give the same results as the
original?
public int refundBalance()
{ balance = 0;
return balance; }
What tests can you run to demonstrate that it
does not?
- Exercise 2.27, page 34.
What happens if you try to compile the
TicketMachine class with the following version of
refundBalance:
public int refundBalance()
{ return
balance; balance =
0; }
What do you know about return statements
that explain why this version is incorrect?
|
2.10 Reflecting on the design of the ticket
machine
- No check that enough money inserted to pay for ticket.
- No check that sensible amount of money inserted, can
insert negative amounts of money.
- No check that ticket price of constructor is sensible.
- No refund when too much money inserted.
2.11 Making choices: the conditional
statement
- Check that enough money inserted to pay for ticket.
- Checks that sensible amount of money inserted, can
insert negative amounts of money.
- No check that ticket price of constructor is sensible.
- No refund when too much money inserted.
| Exercise 9 -
Conditionals
In BlueJ:
- Open the better-ticket-machine project.
- Create a TicketMachine object:
- with a ticketPrice parameter of
25 cents.
- Inspect the object.
- Call insertMoney method with
amount parameter of -45 cents.
- What happened to the object state?
- Call insertMoney method with
amount parameter of 5 cents.
- What happened to the object state?
- Call printTicket method.
- What happened to the object state?
- Explain how total changed.
- Explain how balance changed.
- Call insertMoney method with
amount parameter of 50 cents.
- What happened to the object state?
- Call printTicket method.
- What happened to the object state?
- Explain how total changed.
- Explain how balance changed.
|
-
| if else conditional - When
condition is true, performs the first statement. When condition is
false, performs statement following the else.
|
| Exercise 10 - if else conditionals
What are the following when:
- amount = 54
- balance = 10
- correct = true
- 4 > 5
- if (4 > 5 ) { balance = 6 } else { balance =
7 };
- 4 <= 5
- if ( 4 <= 5) { balance = 6 } else { balance
= 7 };
- "a" < "b"
- "abc" < "ab"
- amount > 50
- if (amount > 50 ) { balance = 6 } else
{ balance = 7 };
- amount -10 > 50
- if (amount - 10 > 50 ) { balance = 6 }
else { balance = 7 };
- if (amount > 0 )
{
balance += amount }
else { System.out.println( "Use a
positive amount: " + amount ); }
- if ( true ) { balance = 6 } else {
balance = 7 };
- if ( correct ) { balance = 6 } else {
balance = 7 };
|
Changes to naive-ticket-machine to make
the better-ticket-machine
public class
TicketMachine { |
public void
insertMoney(int
amount) {
if(amount > 0)
{
balance += amount;
} else
{
System.out.println("Use a positive amount: " +
amount);
} } |
public void
printTicket() {
if(balance >= price)
{
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 +=
price;
balance -= price;
} else
{
System.out.println("You must insert at least: " + (price -
balance) + " more
cents.");
} } |
public int
refundBalance() {
int amountToRefund;
amountToRefund =
balance; balance =
0; return
amountToRefund; } |
|
2.12 A further conditional-statement
example
See printTicket above.
Exercise 11 - printTicket
- Exercise 2.33, page 39. After a ticket has been
printed, could the value of balance field ever be set to a
negative value by subtracting price? Justify your answer.
|
2.13 Local variables
-
| Local variables - Variables
defined inside a method. As with a formal parameter, scope is limited to
inside the method. |
public int
refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0; return
amountToRefund; } |
| Exercise 12 - Local variables
In BlueJ:
- Open the better-ticket-machine project.
- Create a TicketMachine object:
- with a ticketPrice parameter of
25 cents.
- Inspect the object.
- Is amountToRefund variable a field of
the object?
- Call insertMoney method with
amount parameter of 45 cents.
- What happened to the object state?
- Call refundBalance method.
- What happened to the object state?
- What value was returned?
- Add the following line in method
printTicket:
balance -= price; amountToRefund =
0;
- Compile. What does the error message
mean?
- Correct printTicket method by deleting
the added line.
- Change the local variable definition to a
comment as follows:
- Compile TicketMachine.
- Why is there an error message?
- Exercise 2.35, page 40.
- Local variables are temporary. Each time a
method is called, the local variables are created. When the method
returns, the local variables are destroyed.
What is printed by 4 calls to the
method:
public void Exercise12()
{ int count =
0; count = count +
1;
System.out.println(count); } |
|
2.14 Fields, parameters and local
variables
Read text, page 40.
| Exercise 13 - Fields, parameters and local
variables
In BlueJ:
- Exercise 2.36, page 41.
- Add a new TicketMachine method,
emptyMachine, that models emptying the machine of money.
- The method should return the value in
total and set total to 0.
- Create an object with a ticket price of 45
cents.
- Inspect.
- Call insertMoney method with 73 as the
actual parameter.
- Call emptyMachine method to test.
- Exercise 2.37, page 41. Is emptyMachine
an accessor, mutator, or both?
- Exercise 2.38, page 41. Rewrite
printTicket method:
- declare a local variable
amountLeftToPay
- initialize amountLeftToPay to the
difference between price and balance
- Rewrite the conditional to check
amountLeftToPay <= 0
- if true, print a ticket
- else print an error message stating the
amount still required
- Create an object with a ticket price of 45
cents.
- Inspect.
- Test both conditions:
- Call insertMoney method with 44 as
the actual parameter.
- Call printTicket method. Was the
result as expected?
- How can the other condition be tested? Test
to verify.
|
2.15 Summary of the better ticket
machine
- Conditional statement - Performs one of two
statements based on a condition test result.
- Local variables - Temporary variable inside
constructor or method.
2.16 Reviewing a familiar example
private
String name; private String
id; private int
credits; |
|
public Student(String fullName, String
studentID)
{ name =
fullName; id =
studentID;
credits = 0;
} |
|
public String getName()
{ return
name;
} |
|
public void changeName(String
replacementName)
{ name =
replacementName;
} |
|
public String getStudentID()
{ return
id;
} |
|
public void addCredits(int
additionalPoints)
{ credits +=
additionalPoints;
} |
|
public int getCredits()
{ return
credits;
} |
|
public String getLoginName()
{ return
name.substring(0,4) + id.substring(0,3);
} |
|
public void print()
{
System.out.println(name + " (" + id +
")");
} |
|
Exercise 14 - Review and String methods
- "01234567".substring(2,5) is the String "234".
Assume the name field is "012345". What is:
- "01234567".substring(4,5)
- "01234567".substring(4,7)
- "01234567".substring(4,10)
- name.substring(0,3)
- name.substring(-1,3)
- "01234567".length() is the integer 8. Assume
the name field is "012345". What is:
- "01234".length()
- "Harvey".length()
- name.length()
- "01234".substring(1,4).length()
- name.substring(0,5).length()
In BlueJ:
- Open project
C201\Projects\chapter01\lab-classes
- Student class contains how many:
- fields
- constructors
- mutators
- accessors
- What do the accessor names have in common?
- Exercise 2.40, page 44.
- What would be returned by getLoginName
for a student with the name "Henry Moore" and the id "557214"?
- 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?
- Exercise 2.42, page 44.
- Exercise 2.43, page 44.
|
2.17 Summary
private
String author; private String
title; |
|
public Book( String bookAuthor, String bookTitle
) {
author = bookAuthor;
title = bookTitle;
} |
|
| Exercise 15 - Creating a class
In BlueJ:
- Open project
C201\Projects\chapter01\lab-classes
- Exercise 2.45, page 47.
- Exercise 2.46, page 47.
|


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