chapter complete

189
Chapter 1 Objects and Classes 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 19574779 r A LL 0 S earch site Page 1

Upload: gini

Post on 07-Apr-2015

333 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Chapter Complete

Chapter 1Objects and Classes

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 inchescolor      blacklocation row 3, position 2

height   30 inchescolor      tanlocation row 4, position 1

19574779 r

0

Search site

Page 1

Page 2: Chapter Complete

 

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.

 

1.2 Creating Objects

Create object - To create a new instance of a real desk requires lumber, nails, etc. but since we are modeling a desk on a computer two new desk instances are created in Java by:

new Desk()

new Desk()

 

Name object - Naming each desk allows us to distinguish one desk from another by:

Desk desk1 = new Desk()

Desk desk2 = new 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

o On the computer desktop, double-click the icon. Open project shapes

1. Click Project | Open Project 2. Type File Name:

Page 2

Page 3: Chapter Complete

J:\C201\Projects\chapter01 3. Click on:

chapter01 | shapes

You should now see the following indicating that shapes project has been opened:

 

Exercise 3 - Creating objects in BlueJ

1. Right-click on the Circle class icon and choose:o new Circle()

2. Create another circle.3. Create a square.

 

1.3 Calling Methods

Exercise 3 created two circles that included an isVisible field that when false the circle is not visible and when true the circle is visible.

circle_1 circle_2

Page 3

Page 4: Chapter Complete

diameter    30isVisible     false

diameter    30isVisible     false

 

Methods - A method performs action on the object by using the values of the fields.

Method makeVisible() sets the isVisible field to true.

 

Exercise 4 - Calling methods in BlueJ

1. Right-click on circle_1 icon . Choose makeVisible().2. Right-click on circle_1 icon. Choose moveUp(). Repeat several times.3. Make circle_1 invisible and visible several times.

 

1.4 Parameters

Two circles have been created with field values of:

circle_1 circle_2diameter    30isVisible     false

diameter    30isVisible     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().

3. Click on the taskbar icon

.

Page 4

Page 5: Chapter Complete

4. Right-click on circle_1 icon in BlueJ.5. Choose changeSize(int).6. Make circle_1 diameter 150 as at right.7. Figure out how to call slowMoveVertical method.

 

1.5 Data types

Describing real problems as a computer model requires defining the problem data.

The following fields describe circle_1's diameter, visibility, and color.

circle_1int          diameter   30boolean isVisible     falseString    color           "blue"

 

Data type - Specifies the type of data value of a field or parameter.

o int - Integer (whole number). Examples: 34, -25, 9999999, 0. o double - real number. Examples: 14.76, 3963.4, 0.5. o boolean - Either true or false. o String - Anything enclosed in double quotes. Examples: "blue", "12", "Hi there".

Exercise 6 - Calling methods with String parameters

1. Click on the taskbar icon .2. Right-click on circle_1 icon in BlueJ.3. Call changeColor method with parameter "red".4. Call changeColor method with parameter "Mary".5. Call changeColor method with parameter red.6. Call changeColor method with parameter 14.7. Call changeColor method with parameter 'red'.

1.6 Multiple Instances

circle_1 circle_2

Two instances of the Circle classdiameter    30isVisible     false

diameter    30isVisible     false

Page 5

Page 6: Chapter Complete

Class - Defines the fields and methods of objects. An object (instance of the class) can be created.

Objects - An instance of a class. The fields have values and the methods can be called for the object.

Exercise 7 - Multiple Instances

1. Create three Circle objects by right-clicking on .o Make each visible.o Move each around.o Make each a different color.

2. Create two Triangle objects.o Make each visible.o Move each around.o 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_1int          diameter   30int          xPosition   70int          yPosition   60boolean isVisible     falseString    color           "blue"

 

Exercise 8 - Inspecting Object State

1. Click on the taskbar icon .

2. Inspect the state of circle_1 by right-clicking on .o Choose Inspect.o Call changeColor method using a different color parameter.o 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?

Page 6

Page 7: Chapter Complete

2. Are all values the same?4. Inspect a Triangle and Circle object simultaneously.

o What fields are the same?o What fields are different?

 

1.8 What is an object?

Objects - An instance of a class. The fields have values and the methods can be called for the object.

All objects of a class have identical fields; the fields of one object can hold different values from other objects.

Circle class circle_1 object circle_2 objectint          diameter    

int          xPosition int          yPositionboolean isVisibleString    color

int          diameter   30int          xPosition   70int          yPosition   60boolean isVisible     falseString    color           "blue"

int          diameter   30int          xPosition   140int          yPosition   72boolean isVisible     trueString    color           "red"

Methods - A method performs action on the object by using the values of the fields.

All objects of a class have identical methods; methods are called on one, designated object.

Circle methodsvoid changeColor(String)void changeSize(int)void makeInvisible()void makeVisible()void modeDown()

 

Page 7

Page 8: Chapter Complete

Exercise 9 - Using Objects

1. Create a house and sun similar to the picture at right using theshapes project classes Circle, Triangle and Square.

2. Write down what tasks you did; list the objects created and methods called. For Example:

a. Circle circle_1 = new Circle()b. circle_1.makeVisible()

       .       .

3. Could the methods be called in any order?

1.9 Object Interaction

The tasks of Exercise 9 would normally be written as Java instructions that could be performed by the computer rather than entering by hand each time a house is to be drawn. In Exercise 10, the tasks have been listed in the picture project.

Exercise 10 - Object Interaction

1. Open the picture project.a. Click Project | Open Projectb. Type File Name:

J:\C201\Projects\chapter01c. Click on:

chapter01 | picture2. Create an instance of class Picture.3. Call the draw method.

1.10 Source Code

Tasks to create objects and call methods can be written in Java, saved to a file, and reused over and over. The list of Java statements define a new class, the written text of the statements are the source code for the class.

Exercise 11 - Source Code

1. Open the picture project.

2. Right-click on icon .3. Click on Open Editor to see the source code text.4. What is the name of the class?

Page 8

Page 9: Chapter Complete

o Find the statement that defines the name of the class.5. Find the fields for the sun and parts of the house.

o What are the field names?6. Find the public void draw method.

o What are the wall tasks?o 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.

o Change the color of the sun to blue.o Compile by clicking the Compile button (see

figure at right).o What happened to picture_1 object?o Was picture_1 object using the most recent

definition of Picture class?3. Create an instance of class Picture named picture_1.

o 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.

Page 9

Page 10: Chapter Complete

c. Create an instance of class Picture named picture_1.

Call the draw method.5. 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.

o Use the slowMoveVertical(int) method.3. Compile by clicking the Compile button.4. Create an instance of class Picture named picture_1.

o Call the draw method.

o Open the icon to see the results.o Call the draw method again to see the sunset.

 

Exercise 15 - Challenge

1. Open Editor to see the source code text.2. Add a new method named sunset.

o Use public void draw() as a pattern.o 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.

o Call the draw method.

o Open the icon to see the results.o Call the sunset method to see the sunset.

1.11 Another Example

This is a simple example example of a student database that tracks students in a laboratory class and prints class lists.

Exercise 16 - Student Database

1. Open project lab-classes.2. Create a Student object.

o Fill in the name and id fields as String (enclose String's in ").3. Inspect the object.

1.12 Return Values

Page 10

Page 11: Chapter Complete

Calling a method can produce a return value as a result. When the name field is "Jane", the Student class method getName produces the return value "Jane".

Return values - Parameters pass information to a method when called. Methods pass information back as return values.

Signature - Method signature define:

o number of parameterso name of parameterso class of parameterso return value class

Exercise 17 - Return Values of Methods

1. Continue Exercise 16.2. Create two Student objects.

o Fill in the name and id fields with different String values (enclose String's in ").3. Inspect each object.4. Call method getStudentID for each object.5. Find the signature of the getStudentID method.

o Right-click Student classo Open Editor.o What are the parameters?o What class is the return value?o What field is returned?o What is returned for one of the Student objects?

6. Find the signature of the changeName method.o Right-click Student classo Open Editor.o What are the parameters?o What class is the return value?o What field is returned?o What is returned for one of the Student objects?

 

1.13 Objects as Parameters

Any object can be a method parameter, as long as the object class matches the method signature.

Exercise 18 - LabClass

1. Continue Exercise 17.2. Create a LabClass object with maximum of 5 students

o The LabClass constructor signature indicates an int parameter which must be

Page 11

Page 12: Chapter Complete

passed the maximum number of students.3. Call the numberOfStudents method.

o What is the result?

The enrolStudent method is passed a Student parameter.

Exercise 19 - Objects as Parameters

1. Continue Exercise 18.2. Create a Student object with a maximum of 5 students.3. Call enrolStudent method with the name of one Student object as the parameter.

o The enrolStudent signature indicates a Student parameter must be passed.4. Call the numberOfStudents method.

o What is the result?5. Call LabClass method enrolStudent with the same Student object as before.6. Call the numberOfStudents method again.

o What is the result?o What does the method do?

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.

o What does printList the method do?

Exercise 21 - Exploring LabClass

1. Create a LabClass object.o 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: 562. Charlie Simpson, student ID: 12003P, credits: 6

3. Call LabClass method enrolStudent to enter the two Student objects.

o Call the printList method for the LabClass object.

 

Exercise 22 - Exploring LabClass

1. Continue Exercise 21.2. Set the instructor, room, and lab time fields of the LabClass object.3. Call the printList method for the LabClass object.

Page 12

Page 13: Chapter Complete

4. Inspect the LabClass object.

Chapter 2Understanding class definitions

powered by FreeFind

Modified:  08/27/2004 12:17:09

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

1. Open project: C201\Projects\Chapter02\naive-ticket-machine

2. In BlueJ menu:o Click Viewo Check Show

Terminal.3. In Terminal Window:

o Click Optionso Check Record method calls.

4. Create an instance of the class using TicketMachine(ticketCost) constructor.

o Supply an int parameter for the ticketCost in cents for $1.00.

19574779 r ALL

0

Search site

Page 13

Page 14: Chapter Complete

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

o Check the balance.o What is the balance after printTicket method is called?o Is that reasonable?

Exercise 2.3

o Experiment by inserting different amounts of money before calling printTicket method.

o What is the balance after printTicket method is called?o What must happen to balance field in printTicket method?

Exercise 2.4

o Experiment with the TicketMachine class before we examine in in detail.o Create another TicketMachine object with a different ticket price.o Buy and print a ticket.o Does the ticket look much the same?o 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; }

Page 14

Page 15: Chapter Complete

 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

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?

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.

Page 15

Page 16: Chapter Complete

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.

 

Page 16

Page 17: Chapter Complete

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; }

Page 17

Page 18: Chapter Complete

 

Exercise 3 - Formal Parameters, Fields and Scope public int getPrice() {       return price; }

 private int price; private int balance; private int total;

1. What is the formal parameter of insertMoney method?2. What is the formal parameter of getPrice method?3. What is the scope of amount?4. Can balance be used in method getPrice?5. Can amount be used in method getPrice?6. Try in BlueJ.

o In method getPrice change return price; to return amount;o Compile.o 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?

1. balance = 40*3+2;2. name = "Fred" + "Flintstone";3. 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:

Page 18

Page 19: Chapter Complete

 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; }

o Comment - For humans to read. Starts with /* and ends with */o Header - Defines method name, return data type, and formal parameters.o 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

Page 19

Page 20: Chapter Complete

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.

o Remove the return price; statement from getPrice.o Compileo What happened and why?

4. Write an accessor method getTotal that returns the total field value.o Compile and test.

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:o Create a TicketMachine object with a positive ticket price.o 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?

Page 20

Page 21: Chapter Complete

= Assignment only.

+= Add then assignment.Exercise 6 - Assignment

1. What is the value of balance after each statement:

balance = 40;balance = 20;balance = 10;

2. What is the value of balance after each statement:

balance = 40;balance = balance + 20;balance = balance + 10;

3. 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.##################

Page 21

Page 22: Chapter Complete

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 + 5d. "34"+"5"e. "34"+"5"f.  "# " +"price" + " cents."g.  "# + price + cents."

In BlueJ:

4. Create the TicketMachine object above.o Inspect the object.o Call the printTicket method on the object.

5. 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.

6. 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:

Page 22

Page 23: Chapter Complete

The price of a ticket is xyz cents.

where xyz is replaced by the value of price field when the method is called.

7. 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

1. Implement another TicketMachine constructor:o with no ticketPrice parametero price is fixed at 1000 centso create a TicketMachine object using your new constructoro create a TicketMachine object using the old constructor and an actual parameter

for a ticket price of 54 cents.o Inspect both objects. You should have two inspector windows. Is there any

difference in the two objects?o Call insertMoney method using both objects.o Call printTicket method using both objects. Is there any difference in the two

objects?

In your head

2. 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?

3. 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;

Page 23

Page 24: Chapter Complete

        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

1. No check that enough money inserted to pay for ticket. 2. No check that sensible amount of money inserted, can insert negative amounts of

money. 3. No check that ticket price of constructor is sensible. 4. No refund when too much money inserted.

2.11 Making choices: the conditional statement

1. Check that enough money inserted to pay for ticket. 2. Checks that sensible amount of money inserted, can insert negative amounts of money. 3. No check that ticket price of constructor is sensible. 4. No refund when too much money inserted.

Exercise 9 - Conditionals

In BlueJ:

1. Open the better-ticket-machine project.2. Create a TicketMachine object:

o with a ticketPrice parameter of 25 cents.3. Inspect the object.4. Call insertMoney method with amount parameter of -45 cents.

o What happened to the object state?5. Call insertMoney method with amount parameter of 5 cents.

o What happened to the object state?6. Call printTicket method.

o What happened to the object state?o Explain how total changed.o Explain how balance changed.

7. Call insertMoney method with amount parameter of 50 cents.o What happened to the object state?

8. Call printTicket method.o What happened to the object state?o Explain how total changed.o 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

Page 24

Page 25: Chapter Complete

What are the following when:

amount = 54 balance = 10 correct = true

1. 4 > 52. if (4 > 5 ) { balance = 6 } else { balance = 7 };3. 4 <= 54. if ( 4 <= 5) { balance = 6 } else { balance = 7 };5. "a" < "b"6. "abc" < "ab"7. amount > 508. if  (amount > 50 ) { balance = 6 } else { balance = 7 };9. amount -10 > 5010. if  (amount - 10 > 50 ) { balance = 6 } else { balance = 7 };11. if  (amount > 0 ) {

     balance += amount }   else {      System.out.println( "Use a positive amount: " + amount );

}12. if  ( true ) { balance = 6 } else { balance = 7 };13. 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();

Page 25

Page 26: Chapter Complete

              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:

1. Open the better-ticket-machine project.2. Create a TicketMachine object:

o with a ticketPrice parameter of 25 cents.3. Inspect the object.

o Is amountToRefund variable a field of the object?

Page 26

Page 27: Chapter Complete

4. Call insertMoney method with amount parameter of 45 cents.o What happened to the object state?

5. Call refundBalance method.o What happened to the object state?o What value was returned?

6. Add the following line in method printTicket:

balance -= price;amountToRefund = 0;

o Compile. What does the error message mean?

7. Correct printTicket method by deleting the added line.8. Change the local variable definition to a comment as follows:

o // int amountToRefund;9. Compile TicketMachine.

o Why is there an error message?10. Exercise 2.35, page 40.11. 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:

1. Exercise 2.36, page 41.o Add a new TicketMachine method, emptyMachine, that models emptying the

machine of money.o The method should return the value in total and set total to 0.o Create an object with a ticket price of 45 cents.o Inspect.o Call insertMoney method with 73 as the actual parameter.o Call emptyMachine method to test.

2. Exercise 2.37, page 41. Is emptyMachine an accessor, mutator, or both?3. Exercise 2.38, page 41. Rewrite printTicket method:

o declare a local variable amountLeftToPayo initialize amountLeftToPay to the difference between price and balance

Page 27

Page 28: Chapter Complete

o Rewrite the conditional to check amountLeftToPay <= 0 if true, print a ticket else print an error message stating the amount still required

o Create an object with a ticket price of 45 cents.o Inspect.o 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

 public class Student {

    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;

Page 28

Page 29: Chapter Complete

    }

    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

1. "01234567".substring(2,5) is the String "234". Assume the name field is "012345". What is:

1. "01234567".substring(4,5)2. "01234567".substring(4,7)3. "01234567".substring(4,10)4. name.substring(0,3)5. name.substring(-1,3)

2. "01234567".length() is the integer 8. Assume the name field is "012345". What is: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-classeso Examine in the editor.

2. Student class contains how many:o fieldso constructorso mutatorso accessors

3. What do the accessor names have in common?4. Exercise 2.40, page 44.

o What would be returned by getLoginName for a student with the name "Henry Moore" and the id "557214"?

5. Exercise 2.41, page 44.

Page 29

Page 30: Chapter Complete

o 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 {

    private String author;    private String title;    public Book( String bookAuthor, String bookTitle )   {       author = bookAuthor;       title = bookTitle;    }

 }

 

Exercise 15 - Creating a class

In BlueJ:

1. Open project C201\Projects\chapter01\lab-classeso Examine in the editor.

2. Exercise 2.45, page 47.3. Exercise 2.46, page 47.

Chapter 3Object 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

19574779 r

0

Search site

Page 30

Page 31: Chapter Complete

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.

o Inspect the object but don't close.o Call increment() method at least 6 times.o What behavior does a NumberDisplay object exhibit.

3. Create a ClockDisplay object with hour=23 and minute = 58.o Inspect the object but don't close.o Call timeTick() method at least 3 times.o 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.

Page 31

Page 32: Chapter Complete

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

Single clock display - 4 digits for time

Modular display - 2 modules of 2 digits where hour digits range from 00 to 23, minute from 00 to 59.

Modularization divides the single time display to two modules, one for hours and one for minutes. Display of hours is now separate from the display of minutes.

Abstract display - 2 digits where digits range from 00 to an upper limit. Abstraction ignores the detail of the number range difference between hour (00-23) and minute (00-59) module using a variable maximum number range. The hour maximum is 23 and the minute maximum is 59 is the only difference.

From this brief analysis, we see the clock display has 2 number displays for hours and minutes.

3.5 Implementing the clock display

Page 32

Page 33: Chapter Complete

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.

Page 33

Page 34: Chapter Complete

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.o Show any dependency arrows.

2. Sketch the dynamic Object diagram for the person object below after execution of:o Exercise2A person = new Exercise2A("John", "Crab");

o Show reference arrows.3. Sketch the Class diagram for the Exercise2B class below.

o Show any dependency arrows.4. Sketch the Object diagram for the couple object below after execution of:

o Exercise2B couple = new Exercise2B();

o 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.

o int - Integer (whole number). Examples: 34, -25, 9999999, 0. o boolean - Either true or false. o char - One character enclosed in single quotes. Examples: 'a', '4'. o 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.

Page 34

Page 35: Chapter Complete

! - not. Examples: !true is false, !false is true.  

X  !Xtrue falsefalsetrue

&& - and. Result true when both operands are true.  

A  B A && Bfalsefalsefalsefalsetrue falsetrue falsefalsetrue true true

|| - or. Result true when either operand is true  

A  B A || Bfalsefalsefalsefalsetrue truetrue falsetruetrue true true

Exercise 3 - Logical operators

1. What is the result of the following?a. true && falseb. false || truec. true && (false || true)d. !true || falsee. (4 < 5)f. (4 < 5) && (6 >= 5)g. (4 > 5) || (6 <= 5)

 NumberDisplay Source code

 public class NumberDisplay {

 private int limit; private int value;  public NumberDisplay(int rollOverLimit) {     limit = rollOverLimit;     value = 0; }

Page 35

Page 36: Chapter Complete

  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

1. Give the Java code to create a new NumberDisplay object named miles with a rollOverLiimit of 5.

o What is the state of miles?o

2. Give the Java code to set the object miles to 5 using method setValue.o What is the new state of miles?o What would happen if the following were used in setValue:

if((replacementValue >= 0) || (replacementValue < limit))

3. Give the Java code to set the object miles to 4 using method setValue.o What is the new state of miles?o

4. Give the Java code to increment the object miles one time.o What is the new state of miles?

3.8.2 String Concatenation

Concatenation operator - + with one String operand results in a concatenated String.

Examples: o "abc" + "efg" is "abcefg" o 1 + "a" is "1a" o 1 + "2" is "12"

Page 36

Page 37: Chapter Complete

o 1 + "" is "1"

  public String getDisplayValue() {     if(value < 10)          return "0" + value;     else          return "" + value; }

Exercise 4 - getDisplayValue() Analysis

1. For value = 5,  what is: "0" + value2. For value = 5,  what is: "" + value3. Assume NumberDisplay object miles has state:

limit = 10value = 5

What is: miles.getDisplayValue();

4. Assume NumberDisplay object miles has state:

limit = 120value = 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: o 25 % 4 is 1 o 25 / 4 is 6 o 17 % 3 is 2 o ( 16 + 1 ) % 3 is 2 o 17 / 3 is 5 o (16 + 1 ) / 3 is 5

  public void increment() {     value = (value + 1) % limit; }

Exercise 5 - increment() Analysis

1. What are all the possible results of:o n % 4o

Page 37

Page 38: Chapter Complete

2. What are all the possible results of:o n % mo

3. Assume NumberDisplay object miles has state:

limit = 7value = 5

What is: miles.increment();

4. Assume NumberDisplay object miles has state:

limit = 7value = 6

What is: miles.increment();

5. 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

Page 38

Page 39: Chapter Complete

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

1. Open project chapter03\clock-display.2. Create a ClockDisplay object that

corresponds to the object diagram at right.o Inspect the object but don't close.o Call each method.

3. Create a ClockDisplay object with time at 23:58.

4. 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(); }

 }

   

Page 39

Page 40: Chapter Complete

Exercise 7 - Objects creating objects

In your head

Match each of the Java code below with one of the objects created at right.

1. hours = new NumberDisplay( 24 );2. new ClockDisplay( );3. 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; } }

Page 40

Page 41: Chapter Complete

 }

Exercise 8 - Multiple constructors

Match the objects created below with the corresponding Java code, the signature must match the call:

1. ClockDisplay myDisplay = ClockDisplay();2. ClockDisplay myDisplay = ClockDisplay(15, 23 );3. 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: o 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.

o ClockDisplay

  public void setTime(int hour, int minute) {     hours.setValue(hour);     minutes.setValue(minute);     updateDisplay(); }

NumberDisplay

Page 41

Page 42: Chapter Complete

  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.o Example of an external method call:

Page 42

Page 43: Chapter Complete

hours.setValue(hour);

o 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.

o Modify the ClockDisplay constructors to a 12 hour NumberDisplay object.o Modify updateDisplay method to display hour 12 when the object hours value is

0, hour 13 is 1, etc.o 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.

Page 43

Page 44: Chapter Complete

Exercise 9.1 - Breakpoints

In BlueJ

1. Create a

ClockDisplay instance with hour=13 and minute=58.2. Set a breakpoint in ClockDisplay method timeTick.

a. Open the editor for the ClockDisplay class.b. Click on the line to breakpoint, the statement: minutes.increment();c. In the BlueJ menu, click Tools | Set/Clear Breakpoint.

3. Call

ClockDisplay method timeTick. The debugger should highlight the first breakpointed statement encountered in the program.

4. What are the names of the instance variables (or fields) of a ClockDisplay object. See the Debugger window below.

5. Double-click the minutes field to inspect. What is the value?6. Close the inspection window.

3.11.4.2 Single stepping

Single stepping - Executing a single statement.Exercise 9.2 - Single stepping

Page 44

Page 45: Chapter Complete

In BlueJ

1. The minutes.increment(); should be highlighted in the Debugger window.

2. Click Step in Debugger to execute the statement.3. What changed in the Debugger?4. Double-click the minutes field to inspect. What changed?5. Click Step in Debugger to execute the if-statement.

o Which statement was executed?o Why?

Click Continue to complete the method timeTick.

Exercise 9.3 - Single stepping

In BlueJ

1. Call ClockDisplay method timeTick again. The debugger should highlight the first breakpointed statement encountered in the program.

2. What is the statement at the breakpoint again?3. Double-click the minutes field to inspect. What is the value?4. Close the inspection window.5. Click Step in Debugger to execute the statement.6. Double-click the minutes field to inspect. What is the value?7. Close the inspection window.8. Click Step in Debugger to execute the if-statement.

o Which statement was executed?o 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

1. Set a breakpoint at the first statement of method setTime.2. Call method setTime with hour=23 and minute=59. The debugger should highlight the

first breakpointed statement encountered in the program.3. What local variables (or parameters) are listed?4. Click Step to execute until the statement below is highlighted:

Page 45

Page 46: Chapter Complete

oo updateDisplay();o

5. Click Step Into to execute into the updateDisplay method.6. Click Step to follow the execution.7. 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

1. Experiment with the mail-system project.a. Open the mail-system project.b. Create a MailServer object.c. Create two MailClient objects:

i. name the two objects sophie and juan.ii. supply each the MailServer object name just created

iii. give a user name that matches the object's name (i.e. "Sophie" and "Juan").

d. Use the MailClient objects to send and receive messages using:

i. sendMessageii. getNextMailItem or

printNextMailItem2. 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.

 public class

Page 46

Page 47: Chapter Complete

MailItem {

 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

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 47

Page 48: Chapter Complete

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.

3.13.2 Single stepping

Single stepping - Executing a single statement.Exercise 11 - Single stepping

In BlueJ

1. Note there are no local variables listed in the Debugger window.2. What does the statement do at the breakpoint?

oo MailItem item = server.getNextMailItem(user);o

3. Click Step in Debugger to execute the statement.4. What changed in the Debugger?

Page 48

Page 49: Chapter Complete

5. item is a local variable and references the MailItem object for user "Juan".

a. Since "Juan" has mail, which statement would you expect the if-statement to execute next?

b. Is the value of item listed as null or something else?6. Click Step in Debugger to execute the statement.

o Which statement was executed?o Why?

Click Continue to complete the method printNextMailItem.

Exercise 12 - Single stepping

In BlueJ

1. Call MailClient method printNextMailItem on juan. The debugger should highlight the first breakpointed statement encountered in the program.

2. Is the statement at the breakpoint again?oo MailItem item = server.getNextMailItem(user);o

3. Click Step in Debugger to execute the statement.4. item is a local variable and references the MailItem object for what user?

a. Since "Juan" has mail, which statement would you expect the if-statement to execute next?

b. Is the value of item listed as null?5. Click Step in Debugger to execute the statement.

o Which statement was executed?o 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

1. The breakpoint should still be set in method printNextMailItem.2. Use sophie's sendMessage to send a message from "Sophie" to "Juan".

Page 49

Page 50: Chapter Complete

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:

oo item.print();o

7. Click Step Into to execute into the print method.8. Continue to click Step Into to follow the execution.

3.14 Method calling revisited

Exercise 14 - Method calling revisited

In BlueJ

1. Set a breakpoint in the first statement of method sendMessage:oo MailItem mess = new MailItem(user, to, message);o

2. Use sophie's sendMessage to send a message from "Sophie" to "Juan".3. What are the formal parameters (i.e. local variables) listed?4. Click Step to execute new MailItem(user, to, message) method.5. What changed and why?6. Click Continue to complete the execution.7. Use juan's sendMessage to send a message from "Juan" to "Sophie".

o Repeat 3-6 again.

Page 50

Page 51: Chapter Complete

Chapter 4Grouping Objects

FreeFind

Modified:  08/27/2004 12:26:21

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

1. Open project chapter04\notebook1.2. Click View | Show Terminal3. In Terminal window click Options | Record method calls4. Create a NoteBook object.

o Add two notes:1. "Buy bread"2. "Sell car"

o Check the number of notes stored.o Show each note. The first note is numbered 0, the second 1, etc.

19574779 r

0

Search site

Page 51

Page 52: Chapter Complete

4.3 A first look at library classes

Collections - An object that can store a arbitrary number of other objects.

Examples:

drawer object can hold arbitrary number of other objects: socks, rocks, spoons, forks, photographs.

note book object can hold arbitrary number of other objects: shopping list, reminders, class notes, etc. Important that each page is arranged in numerical order, page 0, page 1, ...

ArrayList object can hold arbitrary number of other objects: Strings, ClockDisplay, etc.

Class libraries - A class that is already defined and can be used in your program. Similar classes are normally grouped together as a library.

Package - What Java calls a library of classes.

Example packages:

java.util - Utility classes. java.net - Networking classes. java.Math - Math classes.

4.3.1 An example using a library

 import java.util.ArrayList;

 public class Notebook {

  private ArrayList notes;   public NoteBook()  {       notes = new ArrayList();  }

   public void storeNote(String note)  {       notes.add(note);  }   public int numberOfNotes()  {      return notes.size();

Page 52

Page 53: Chapter Complete

  }

   public void showNote(int noteNumber)  {      if(noteNumber < 0) {                                 // Not valid note number, so do nothing.      }      else if(noteNumber < numberOfNotes()) { // Valid note number, so print it.            System.out.println(notes.get(noteNumber));      }      else {                                                        // Not valid note number, so do nothing.      } }

Using the ArrayList class:

import java.util.ArrayList; - Gain access to the library. private ArrayList notes; - Define field notes as type ArrayList class. notes = new ArrayList() - Create an instance of ArrayList.

ArrayList methods:

The ArrayList class supplies many useful methods, we will use four for now:

1. add - adds an object to the ArrayList. Example: o notes.add("Take vacation");

2. size - returns the number of objects in the ArrayList. Example (assuming 3 objects):

o notes.size(); returns 3. 3. get - returns the ith object in ArrayList. Example:

o notes.get( 2 ); returns the 2nd object from ArrayList notes. 4. remove - removes the ith object in the ArrayList. Example (assuming 3 objects):

o notes.remove(1);

4.4 Object structures with collections

ArrayList object notes after the following statements are executed: 1. private ArrayList notes; 2. notes = new ArrayList(); 3. notes.add("Buy bread");

Page 53

Page 54: Chapter Complete

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:

o showNote to show note number 1.o numberOfNotes.

3. Store another note "11:30 mtg"o What is the number of this note?o What is the value of: notes.size()?

4. In what order does ArrayList objects store objects?5. 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 54

Page 55: Chapter Complete

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:

o notes.get(1);o notes.get(0);o notes.get(5);o System.out.println( notes.get( 1 ) );

4.6 Removing an item from a collection

remove - removes the ith object in the ArrayList. Example (assuming 3 objects):

Exercise 4 - remove

1. What is the index of "11:30 mtg" after:o notes.remove(1);

2. What is the value now of:o  notes.size()

3. Add the mutator method deleteNote that removes the ith index note from the notebook. Assume the ith note exists.

4. Create a NoteBook object with 3 notes.o Inspect the object.o Inspect notes.o Inspect elementData.o Use deleteNote to remove note at index 1.o Use deleteNote to remove note at index 4.

4.7 Processing a whole collection

Page 55

Page 56: Chapter Complete

listNotes -  We need a NoteBook method that prints all notes along with their index numbers to the terminal window.

Exercise 5 - listNotes

1. Which of the signatures would be most appropriate:a. public ArrayList listNotes()b. public void listNotes(int index)c. public int listNotes()d. public void listNotes()

2. Index 0 holds the first note, index 1 the second, etc. What is wrong with the following as the body for listNotes method?

System.out.println( notes.get(0) );System.out.println( notes.get(1) );System.out.println( notes.get(2) );       :

4.7.1 The while loop

loop - Executes a block of statements repeatedly instead of programmer writing repeatedly. Loops scale very well.

Examples that produce the same result on each row:

Write repeatedly Execute repeatedly

int i = 0;i = i + 1;i = i + 1;i = i + 1;i = i + 1;

int i = 0;while ( i <= 4 ) {     i = i + 1;}

int i = 4;i = i - 1;i = i - 1;i = i - 1;i = i - 1;

int i = 4;while ( i > 0 ) {     i = i - 1;}

int i = 0;i = i + 1;System.out.println( i );i = i + 1;System.out.println( i );i = i + 1;System.out.println( i );i = i + 1;System.out.println( i );

int i = 0;while ( i <= 4 ) {     i = i + 1;     System.out.println( i );}

System.out.println( notes.get(0) );System.out.println( notes.get(1) );

int i = 0;while ( i <= 5 ) {

Page 56

Page 57: Chapter Complete

System.out.println( notes.get(2) );System.out.println( notes.get(3) );System.out.println( notes.get(4) );System.out.println( notes.get(5) );

     System.out.println( notes.get( i ) );     i = i + 1;}

if (notes.size() > 0)    System.out.println( 0 + ":" + notes.get(0) );if (notes.size() > 1)    System.out.println( 1 + ":" + notes.get(1) );if (notes.size() > 2)    System.out.println( 2 + ":" + notes.get(2) );if (notes.size() > 3)    System.out.println( 3 + ":" + notes.get(3) );

int i = 0;while ( i < notes.size() ) {    System.out.println( i + ":" + notes.get( i ) );    i = i + 1;}

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.

o Create an instance with 2 notes and call the listNotes method.

2. Modify listNotes method to print the notes in reverse order.

o 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.

Page 57

Page 58: Chapter Complete

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:

while( true )    

System.out.println( "Forever...");

Stopping - In BlueJ an infinite loop can often be stopped by: o Click which runs the Debugger. o Click Halt button.

Task Manger - When BlueJ cannot stop a run away program, Windows Task Manager can.

o Press Ctrl-Alt-Del keys simultaneously, to run the Task Manager. o Select the Processes tab and locate the java.exe process. o Select the java.exe process and click End Process. o This will end BlueJ.

Exercise 6.1 - Infinite loops

In BlueJ

Copy and paste the following method into the NoteBook class.

public void infinite() {     while( true )            System.out.println( "Forever...");}

Test by calling the method. Stop by:

Page 58

Page 59: Chapter Complete

o Pressing Ctrl-Shift-R keys simultaneously.o or

Right click . It may take a little time to respond. Click Reset Virtual Machine.

BlueJ often becomes somewhat unstable. Suggest closing and restarting BlueJ.

4.7.2 Iterating over a collection

iterator - An object that provides the ability to iterate over every element in a collection.

Example that produce the same result:

System.out.println( notes.get(0) );System.out.println( notes.get(1) );System.out.println( notes.get(2) );

Iterator i = notes.iterator();

System.out.println( i.next( ) );System.out.println( i.next( ) );System.out.println( i.next( ) );

int i = 0;

while ( i < notes.size() ) {    System.out.println( notes.get( i ) );    i = i + 1;}

Iterator i = notes.iterator();

while ( i.hasNext() ) {    System.out.println( i.next()  );}

Iterator i - Defines i of type Iterator. notes.iterator() - Returns an Iterator object for the notes ArrayList collections. i.hasNext() - Returns true if there are more objects in the collection. i.next() - Returns the current object in the collection and iterates to the next object.

Exercise 7 - Iterators

1. From the diagram at right, what is printed by:

Iterator theIter = notes.iterator();

Page 59

Page 60: Chapter Complete

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( ) );

4.7.3 Index access versus iterators

index - notes.get( 3 ); The index allows any object in the collection to be accessed in any order.

iterator - notes.next( ); The iterator access is strictly sequential order.

4.7.3.1 Grouping objects complete example - a party

The following classes define a Person with an age and name, and a Party class that groups Person objects. The class definitions follow:

public class Person {   private int age;   private String name;

   public Person(int newAge, String newName) {      age=newAge;      name=newName;   }

   public int getAge() {      return age;   }

   public void printPerson() {      System.out.print("Name: " + name);      Systen.out.println(" Age: " + age );   }}

import java.util.ArrayList;import java.util.Iterator;

public class Party{   private ArrayList guests;

   public Party() {      guests = new ArrayList();   }

   public void arrive( Person partier ) {      guests.add( partier );   }

   public void indexPrintParty() {      int i = 0;      while (i < guests.size())       {         ((Person) guests.get(i)).printPerson();         i = i + 1;

Page 60

Page 61: Chapter Complete

      }   }

   public void iteratorPrintParty() {      Iterator git = guests.iterator();      while ( git.hasNext() )          ((Person) git.next()).printPerson();   }}

Exercise 7.1 - Example

In BlueJ

1. Create a new project named Exercise 7.1

2. Create a new class named Persono Copy and paste the Person class above.

3. Create a new class named Partyo Copy and paste the Party class above.

4. Duplicate in BlueJ the results of the following:

Person p0 = new Person(43, "George");Person p1 = new Person(29, "Sally");

Party wedding = new Party();wedding.arrive( p0 );wedding.arrive( p1 );

5. Give the object diagram for Question 4.

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)).printPerson();

The following method call succeeds because the compiler does know the class of the object retrieved from the guests ArrayList:

Page 61

Page 62: Chapter Complete

((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.

2. For the object diagram, what is:a. p1.printPerson();b. ((Person) guests.get(1))c. ((Person) guests.get(1)).printPerson();d. wedding.indexPrintParty();e. wedding.iteratorPrintParty();

3. Write the Party method leave(int) that removes the Person at a specified index.

4. Write the Party method to compute the average age. You will need to use the getAge() method for a Person.

4.10 Fixed size collections

array - A collection that can store a fixed number of elements (objects or primitive-type). Uses a special syntax to access elements in the collection.

 

Operations - Only two operations are defined on fixed size array variables. o Assignment - x[ index ] = y; o Copy - y = x[ index ];

Examples that produce the same result

int x0;int x1;int x2;

x0 = -3;x1 = -5;x2 = -4;

int sum = x0 + x1 + x2;

int x[ ] = new int [ 3 ];

x[ 0 ] = -3;x[ 1 ] = -5;x[ 2 ] = -4;

int sum = x[ 0 ] + x[ 1 ] + x[ 2 ];

Page 62

Page 63: Chapter Complete

String notes0 ;String notes1 ;String notes2 ;

notes0 = "Buy bread";notes1 = "Sell car";notes2 = "11:30 mtg";

String  notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";notes[ 1 ] = "Sell car";notes[ 2 ] = "11:30 mtg";

ArrayList notes = new ArrayList( );

notes.add( 0 ) = "Buy bread";notes.add( 1 ) = "Sell car";notes.add( 2 ) = "11:30 mtg";

String notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";notes[ 1 ] = "Sell car";notes[ 2 ] = "11:30 mtg";

System.out.println( notes.get(0) );System.out.println( notes.get(1) );System.out.println( notes.get(2) );

System.out.println( notes[ 0 ] );System.out.println( notes[ 1 ] );System.out.println( notes[ 2 ] );

int i = 0;

while ( i < notes.size() ) {    System.out.println( notes.get( i ) );    i = i + 1;}

int i = 0;

while ( i < notes.length ) {    System.out.println( notes[ i ] );    i = i + 1;}

Page 63

Page 64: Chapter Complete

Exercise 8 - Fixed size collections

String notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";notes[ 1 ] = "Sell car";notes[ 2 ] = "11:30 mtg";

1. From the diagram at right, what is the result:

a. String s = notes[ 2 ];b. notes[ 1 ] =

notes[ 0 ];c. notes[ 2 ] = "Take a

break";d. notes[ 3 ] = "Broke";e. notes[ -1 ] = "Broke";

2. From the diagram at right, what is printed by:

int i = 2;

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.

4.10.a Declaring array variables

Examples:

Declare an array variable hours that can refer to an array of ints: o int[ ] hours;

Declare an array variable months that can refer to an array of Strings: o String[ ] months;

4.10.b Creating array objects

Examples:

Create an array of 24 ints and assign to hours: o hours = new int[24];

Page 64

Page 65: Chapter Complete

Create an array of 12 Strings and assign to months: o months = new String[12];

Exercise 9 - Arrays

1. Write a declaration for an array variable people that can refer to an array of Person objects.

2. Assign variable people an array of 30 Person objects.3. Write a declaration for an array variable vacant that can refer to an array of booleans.4. Assign variable vacant an array of 13 booleans.5. Write a declaration for an array variable dim that can refer to an array of ints.6. Assign dim an array of 12 ints.

4.10.c Using array objects

Indexing - Accessing individual variables of an array using the [ ].

Examples:

Assign hours index 20 value 54: o hours[20] = 54;

Assign months index 2 value "March": o months[2] = "March";

Add hours index 23 value to variable count: o count = count + hours[23];

Print months index 2 value: o System.out.println(months[2]);

Exercise 10 - Using Arrays

1. Initialize each variable (i.e. index) of dim with the number of days in January, February,

Page 65

Page 66: Chapter Complete

etc. for this year.2. Sum index 5, 6 and 7 of dim to variable summer.3. Print index 5, 6 and 7 of dim.

4.10.d The for-loop

for-loop - Iterates from a starting value to an ending value in designated steps.

Example that produce the same result:

ArrayList notes = new ArrayList( );

notes.add( 0 ) = "Buy bread";notes.add( 1 ) = "Sell car";notes.add( 2 ) = "11:30 mtg";

String notes[ ] = new String[3];

notes[ 0 ] = "Buy bread";notes[ 1 ] = "Sell car";notes[ 2 ] = "11:30 mtg";

int i = 0;

while ( i < notes.size() ) {    System.out.println( notes.get( i ) );    i = i + 1;}

int i = 0;

while ( i < notes.length ) {    System.out.println( notes[ i ] );    i = i + 1;}

int i;

for ( i=0; i < notes.size() ; i++) {    System.out.println( notes.get( i ) );}

int i;

for ( i=0; i < notes.length; i++ ) {    System.out.println( notes[ i ] );}

Examples:

Page 66

Page 67: Chapter Complete

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 ];

Print all variables in array hourCounts:

for ( int i = 0; i < 24; 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 ];

    

Exercise 11 - for loop with Arrays

1. Print all the integers from 12 to 3.2. Print all variables in array hourCounts in reverse order.3. Print all the variables in array dim.4. Print all the variables in array dim in reverse order.5. Total all the variables in array dim.6. Find smallest value in array dim.

4.10.1 A log-file analyzer

Page 67

Page 68: Chapter Complete

Web-servers log client visits to web pages.

Analyzing the log file can determine:

popular pages broken links (missing

pages) server usage busy periods

We have a web log file in the format of:

year         month   day     hour   minute

2002         5     01     00     192002         5     01     01     272002         5     01     02     17

 public class LogAnalyzer {

 private int[ ] hourCounts; private LogfileReader reader;   public LogAnalyzer()  {        hourCounts = new int[24];       reader = new LogfileReader();   }

   public void analyzeHourlyData()  {       while(reader.hasMoreEntries()) {              LogEntry entry = reader.nextEntry();              int hour = entry.getHour();              hourCounts[hour]++;       }  }  public void printHourlyCounts() {       System.out.println("Hr: Count");       for(int hour = 0; hour < hourCounts.length; hour++)       {              System.out.println(hour + ": " +

LogAnalyzer - Constructor

hourCounts - Assigned object of fixed array of 24 ints.

reader - Assigned LogfileReader object.

analyzeHourlyData - Fills hoursCountarray with total of the number of visits within an hour period.

For example, adds 1 to arrayindex 5 of hourCounts for a log entryat 5 o'clock. Consider when hour = 5:

     int hour = entry.getHour();     hourCounts[hour]++;

printHourlyCounts - Prints each of the 24 variables in the hourCounts array.

The hoursCount array above

Page 68

Page 69: Chapter Complete

hourCounts[hour]);       } }

   public void printData()  {       reader.printData();  } }

would print:

     0:0     1:5     2:0     3:0     4:2

 

 public class LogAnalyzer {

 private int hourCounts; private LogFileReader reader; Constructor and methods omitted

 }

4.10.2 Declaring array variables

4.10.3 Creating array objects

 

The following creates the array at right:

 private int[ ] hourCounts;   public LogAnalyzer()  {        hourCounts = new int[24];    }

Page 69

Page 70: Chapter Complete

4.10.4 Using array objects

4.10.5 Analyzing the log file

printHourlyCounts - Prints each of the 24 variables in the hourCounts array.

The hoursCount array at right would print:

     0:0     1:5     2:0     3:0     4:2       :

  public void printHourlyCounts() {       System.out.println("Hr: Count");       for(int hour = 0; hour < hourCounts.length; hour++)       {              System.out.println(hour + ": " + hourCounts[hour]);       } }

4.10.5.1 Arrays of objects

Fixed size arrays can hold:

primitive types (int, double, boolean) as seen above references to objects as seen below

Array define - The following defines tms as a TicketMachine array object at right, assuming the TicketMachine definition of Chapter 2):

private tms[ ] TicketMachine;

Array create and assign - The following creates a fixed size array of 3 TicketMachines and assigns the object reference to tms:

Page 70

Page 71: Chapter Complete

tms = new TicketMachine [ 3 ];

Object create and assign - The following creates 3 TicketMachines and assigns each to one of the indexed variables of the array:

tms [ 0 ] = new TicketMachine ( 40 );tms [ 1 ] = new TicketMachine ( 50 );tms [ 2 ] = new TicketMachine ( 60 );

Array use - The following calls the insertMoney(), emptyMachine() and printTicket() methods using TicketMachine numbered 2.

tms [ 2 ].insertMoney ( 70 );tms [ 2 ].printTicket (  );System.out.println( tms [ 2 ].emptyMachine( ) );

 

Exercise 12 - Array of objects

In your head

What ticket is printed in the previous example? What is printed by: System.out.println( tms [ 2 ].emptyMachine( ) ); ?

4.10.6 The for loop

Exercise 13 - for loop

In your head

1. Complete the numberOfAccesses method below to count the total number of accesses recorded in the log file. Complete using a for loop iterating over the hourCounts array.

public int numberOfAccesses() {    int total = 0;

// total each variable of hourCounts

    return total;}

Page 71

Page 72: Chapter Complete

In BlueJ

2. Add numberOfAccesses method to LogAnalyzer class and test.

 

Exercise 14 - for loop

In your head

Three TicketMachines below are:o definedo createdo money insertedo emptied and totaled

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;

Chapter 5 19574779 r

ALL 0

Page 72

Page 73: Chapter Complete

More Sophisticated Behavior

 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.

Exercise 1 - TechSupport class

In BlueJ

1. Open project chapter05\tech-support1.2. Create a SupportSystem object.

o Call the start() method.o Ask questions of SupportSystem.o Type "Bye" to finish. Did it work?o Type " bye" to finish. Did that work?

5.2.2 Reading the code

  public class SupportSystem {

   private InputReader reader;   private Responder responder;   public SupportSystem()  {     reader = new InputReader();     responder = new Responder();

ALL 0

Search site

Page 73

Page 74: Chapter Complete

   }

    public void start()   {      boolean finished = false;      printWelcome();

      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.");   }

    private void printGoodbye()   {          System.out.println("Nice talking to you. Bye...");   } }

 

  public class Responder {

   public Responder()  {   }   public String generateResponse()   {        return "That sounds interesting. Tell me more...";   }

 }

String comparisions

Page 74

Page 75: Chapter Complete

"Edward".startsWith("Ed") - True because "Edward" starts with "Ed". "Edward".startsWith("rd") - False because "Edward" does not starts with "rd". input.startsWith("bye") - True when "bye" is at the beginning of input String,

otherwise false. "Edward".equals("Edward") - True. "Edward".equals("edward") - False.

 

Exercise 2 - Reading the code

In your head

1. What will the following Java statements do? Will printGoodbye()  be executed?

    public void start()   {      boolean finished = 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.o The start() method will not finish until bye is read.o 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().

o  boolean finished = false;4. Call the start() method.

o Use Step to trace the execution of the method.5. What is your response when the following is executed?

o String input = reader.getInput();

Page 75

Page 76: Chapter Complete

o Type something into Terminal Window.o What is the value of input?

6. Use Step Into to execute completely:o String response = responder.generateResponse();o What is the value of response?

5.3 Reading class documents

Java standard library documentation - Details all classes in Java library.Exercise 3 - Java Documentation

In BlueJ

1. Click Help in upper-right corner.2. Click on Java Class Libraries.

o A browser window should open to the Sun Java website.3. Find help on the String class.4. Find help on the startsWith method.

5.3.2 Using library-class methods

Immutable objects - An object, that once created, its state cannot be changed.

Improvements to TechSupport

trim - Allow spaces around "bye" to stop iteration. 

o " a b c ".trim is "a b c" o (input.trim()).startsWith("bye") trims the blanks and tests that result starts with

"bye" 

toLowerCase - Allow "Bye", "BYE", etc. to stop iteration. 

o "AbC".toLowerCase is "abc" o "   AbC   ".toLowerCase().trim() is "abc" o  input.trim().toLowerCase().startsWith("bye") trims the blanks, converts to

lowercase and tests that result starts with "bye". 

Exercise 4 - trim and toLowerCase

In BlueJ

1. Change TechSupport method start() to finish when leading, trailing blanks and uppercase characters entered for bye.

Page 76

Page 77: Chapter Complete

2. Test.3. Can the improvement be written another way?

5.3.3 Checking string equality

Testing for "bye" at the start of input, even with our improvements, behaves incorrectly on input such as "Byelection". We will finish execution only on input of "bye" by testing for equality.

equals - Returns true when two strings are equal. 

o "AbC".equals("AbC") is true. o "AbC".equals("ABC") is false. o  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. 

o 4 == 3 is false. o 4 == 4 is true. o private TicketMachine t1;

private TicketMachine t2;t1 = new TicketMachine(50);t2 = t1;

t1 == t2 is true because both reference the same TechSupport object. 

Exercise 5 - equals and ==

In your head

1. '3' == 3?2. private TicketMachine t1;

private TicketMachine t2;t1 = new TicketMachine(50);t2 = new TicketMachine(50);

t2 == t1?

In BlueJ

1. Change TechSupport method start() to finish when input is only bye using the equals method.

2. Test.

5.4 Adding random behavior

Page 77

Page 78: Chapter Complete

Random behavior is observable in games of chance and real-life. Randomness in computer models is produced by generating pseudorandom numbers. True random numbers never recur in the same sequence but pseudorandom numbers do repeat eventually.

5.4.1 The Random class

The following simulates throwing two dies in a dice game.

import java.util.Random; - Uses the Java library class Random. generator = new Random(); - The object of class Random is named generator. generator.nextInt(6) - Generates the next integer between 0 and 5 inclusive of

the pseudorandom sequence.

 import java.util.Random;

 public class Dice {

  private Random generator;   public Dice()  {       generator = new Random();  }

   public void twoDie()   {       System.out.println( oneDie() + " " + oneDie() );   }   public int oneDie()  {        return generator.nextInt(6)+1;  }

 }

 

Exercise 6 - Random

In BlueJ

1. Create a new project named Exercise6.2. Create a new class named Dice.

o Open the Dice class.o Copy and paste the above class into the Dice class source code.

3. Compile and test by calling the methods:o  oneDie()o twoDie()

4. Do the results appear random?5. What does the following do?

Page 78

Page 79: Chapter Complete

o generator.nextInt(6)+1

 

Exercise 6.5 - Random

In BlueJ

1. Add the method throw() that throws the die 100 times and prints the number of 1, 2, 3, etc.

o Create an array of 6 integers named count.o Initialize the array variables to 0.o For each throw of the die, use the die number as the index of the array variable

to increment.  int n = generator.nextInt(6); count[ n ] = count[ n ] + 1;

o Print all 6 array variables.

5.4. Generating random responses

Exercise 7 - Random responses

In BlueJ

1. Change oneDie() method to return Strings: one, two, three, four, five, or six.

o Hint: int n = generator.nextInt( 6 )+1;        if ( n == 1 ) return "one"         else ...

2. Change oneDie() method to use an ArrayList rather than if-statement.

o Hint: ArrayList words = new ArrayList();        words.add("one");                       // "one" is at index 0                 :        int n = generator.nextInt(6);        // n is 0-5

        return words.get( n );                  // Return object at index n

Responder class with random responses, see project tech-support2.

  public class Responder {

 private Random randomGenerator; private ArrayList responses; public Responder() {

Page 79

Page 80: Chapter Complete

     randomGenerator = new Random();     responses = new ArrayList();     fillResponses(); }

  public String generateResponse() {    int index = randomGenerator.nextInt( responses.size() );    return (String) responses.get(index); }  private void fillResponses() {    responses.add("That sounds odd. Could you describe that problem in more detail?");    responses.add("No other customer has ever complained about this before. \n" +                           "What is your system configuration?");    responses.add("That sounds interesting. Tell me more...");    responses.add("I need a bit more information on that.");    responses.add("Have you checked that you do not have a dll conflict?");    responses.add("That is explained in the manual. Have you read the manual?");    responses.add("Your description is a bit wishy-washy. Have you got an expert\n" +                           "there with you who could describe this more precisely?");    responses.add("That's not a bug, it's a feature!");    responses.add("Could you elaborate on that?"); }

 }

5.5 Packages and imports

Packages contain libraries of Java classes not automatically part of the Java language. import class name makes the package of classes available in a program. For example:

  o import java.util.ArrayList;            Makes just the ArrayList class available. o import java.util.*;                       Makes all classes in the package available.

5.6 Using maps for associations

Map - A collection that associates a fixed pair consisting of a key and a related value. The key maps to the value.

Examples:

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.

Page 80

Page 81: Chapter Complete

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", "VI"); }

  public String translate(String english) {       return (String) englishToroman.get(english); } }

 

Exercise 8 - Mappings

Page 81

Page 82: Chapter Complete

In your head

1. From the object diagram, are the HashMap keys in any obvious order?2. What is the result of the following?

o englishToroman.get("five");o englishToroman.get("four");o englishToroman.get("english");

3. Is (String) really necessary for:o return (String) englishToroman.get(english);

In BlueJ

1. Create a new project named Exercise8.2. Create a new class named Mappings.

o Open the Mappings class.o Copy and paste the above EnglishToRoman class into the source code.o Modify to map SSN (social security number) as Strings to peoples names.

3. Compile:o Test by calling the methods to map SSN to a name.o Test by calling the methods to map name to a SSN.o What happened?

4. Add the same SSN twice to the mapping but with different names.o Test by calling the methods to map that SSN to a name.o What happened?

5. Use the Help in upper-right corner. A browser window should open to the Sun Java website.

o Find help on the HashMap class.o Find out how to check whether a given key is in a map.

5.6.3 Using a map for the TechSupport system

Responder class with HashMap, responds to a given word in the map by returning an associated string.

  public class Responder {

 private HashMap responseMap; public Responder() {     randomGenerator = new Random();     responsesMap = new HashMap();     fillResponses(); }

  public String generateResponse(String word) {    return (String) responsesMap.get(word); }

Page 82

Page 83: Chapter Complete

  private void fillResponses() {     responseMap.put("crash",         "Well, it never crashes on our system. It must have something\n" +        "to do with your system. Tell me more about your configuration.");    responseMap.put("crashes",         "Well, it never crashes on our system. It must have something\n" +        "to do with your system. Tell me more about your configuration.");    responseMap.put("slow",         "I think this has to do with your hardware. Upgrading your processor\n" +        "should solve all performance problems. Have you got a problem with\n" +        "our software?"); }

 }

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;          }          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:o String input = reader.getInput();

2. What is:

Page 83

Page 84: Chapter Complete

o input.startsWith("bye")o responder.generateResponse(input);

5.10 Writing class documentation

Documentation - Should provide enough details that other programmers do not need to examine the source code.

5.10.1 Using javadoc in BlueJ

javadoc - listNotes -  We need a NoteBook method that prints all notes along with their index

numbers to the terminal window.

Exercise 10 - Documentation

1. Open the project Exercise8 and the Mappings class.2. On the BlueJ menu, select Tools | Project Documentation | Regenerate3. Note the documentation generated.4. Add the following comments along with your name; documentation must be placed after

the import:

import java.util.HashMap;

/*** This class implements an English number to Roman numerical translation.* * @version 1.0* @author Your Name*/

public class EnglishToRoman

5. Regenerate the documentation.

5.11 Public versus private

Access modifiers - Define the visibility of a field, constructor or method.Public - Defines the element accessible inside the same class or outside the class.Private - Defines the element accessible only inside the same class

Exercise 11 - Public/Private

In BlueJ

Page 84

Page 85: Chapter Complete

1. Open the TechSupport class.o Note private and public methods.

2. Create a TechSupport object.o Which of the methods can be called?

5.11.1 Information hiding

Information hiding - Principle that internal class implementation details should be hidden from outside the class.

The private keyword hides information making it only accessible inside a class. This prevents accidental or purposeful access to class fields, methods and constructors.

Need to know - One should not need to know class implementation details to use a class.

Not allowed to know - Does not allow access from outside the class.Exercise 12 - Public/Private

In your head

In the TechSupport class.o Do you need to know that a Responder class object is one of the fields?o When calling TechSupport methods, are you allowed to know about fields or

certain methods?o When calling TechSupport methods, are you allowed to know about

constructors?

5.11.2 Private methods and public fields

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

Page 85

Page 86: Chapter Complete

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.

o Call drawdemo method.o Call bounce method.

3. In BlueJ menu:o Open Toolso Project Documentationo Regenerate

4. Read Canvas documentation and from it:o Draw a circle.o Draw a rectangle.

5.13 Class variables and constants

class or static variable - A field having one copy used by all objects. Each object has own version of regular (non-static) field.instance variable - A field having one copy per object.

5.13.1 The static keyword

 public class Test {    private static int count = 0;    private           int i = 0;

    public Test()     {        count = count + 1;        i = i + 1;    }

    public int getCount()    {        return count;    } }

After:

new Test( ); new Test( );

Page 86

Page 87: Chapter Complete

class variable - A single count variable is accessible by all Test objects. instance variable - Each object has its own variable i.

5.13.2 Constants

final - Defines a constant, a value that cannot change.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.

o Inspect two objects.o Show static fields.o 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?

Chapter 6Well-behaved Objects

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

19574779 r

ALL 0

Search site

Page 87

Page 88: Chapter Complete

testing small units automating test manual testing debugging

o print statements o 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-prototype2. Select Day class.

o Click Tools.o Project Documentation.

3. What are the stated values of the dayNumber parameter to the Day constructor?o Would you expect it to work for those values?o What about other values?

4. Construct a Day object.o Are you testing a unit or the complete diary application?

5. Construct another Day object using dayNumber 367.o 367 exceeds the stated Day constructor boundary condition.  Did the

constructor fail?o Do you think something will eventually fail later?o Is it better to fail if the stated operating conditions are violated or try to give

some response?o What is another boundary condition?

6.2.1 Using inspectors

Exercise 1.5 - Inspectors

In BlueJ

1. Construct a Day object.o Inspect the Day object to determine if enough space is available for storing

hourly appointments that start at 9am and run until 6pm?2. Construct three Appointment objects of 1 hour duration.

o Make appointments for 9am, 1pm and 5pm.o Inspect the Day object to verify that the appointments occupy the correct

positions.o What is the Day class makeAppointment method boundary condition? Test it.o Test whether two appointments can be scheduled at the same time.

3. Have you just performed unit or application testing?

Page 88

Page 89: Chapter Complete

6.2.2 Positive versus testing

positive testing - Testing cases that are expected to succeed.

negative testing - Testing cases that are expected to fail.Exercise 2 - Positive and negative testing

In BlueJ

1. Construct one Appointment object of 10 hour duration and construct a Day object.o Make an appointment starting at 9am.o What did your test indicate?o Did the makeAppointment method work as specified?o What were the makeAppointment method specifications?

2. Have you just performed positive or negative testing?3. Can you think of another, similar test for the makeAppointment method?

6.3 Test automation

test automation - Test using a program (testing harness) rather than manually. Favored because repeatable, easier and more reliable than manual testing or inspection.

6.3.1 Regression Testing

regression testing - Because corrections or other changes can introduce errors, earlier tests must be performed again.

The following class automates tests for Exercise 3.

  public class Exercise3Tests {

   public Exercise3Tests()  {   }   public void test()   {        Day day4 = new Day( 4 );        Appointment appt10 = new Appointment("Sleep all day", 10);        day4.makeAppointment( 9, appt10 );   }

Page 89

Page 90: Chapter Complete

 }

 

Exercise 3 - Test automation

In BlueJay

1. Create a new class Exercise3Tests in the diary-prototype project.

o Copy and paste the above class.o The class diagram should appear as

at right.

2. Create an Exercise3Tests object.o Call method test().o Did the automated test produce the

same results as the manual tests?o Is this a good test to automate?

3. Change the test() method to:o Construct a Day object.o Construct three Appointment objects of 1 hour duration.

Make appointments for 9am, 1pm and 5pm.o Test that appointments are placed at the correct times using the Day class

showAppointments() method.o Test whether two appointments can be scheduled at the same time.

6.3.2 Automated checking of test results

Automated testing ensures that critical tests can be easily and routinely performed after each program change.

Automated tests return true only when the test performs correctly. Multiple automated test results are combined using the && (and) operator or &=.

Exercise 5 - Automation of tests

In BlueJ

1. Change the test() method of Exercise 3 to return a boolean type.

2. The result returned should be the conjunction (&&) of the appointments for 9am, 1pm and 5pm.

o Note that makeAppointment returns false if the appointment is not made.o Combine the results of the three makeAppointment calls using &&.o Call your test() method.

3. Change one of the appointments to 6pm and call your test() method again.o Is this a positive or negative test?

Page 90

Page 91: Chapter Complete

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?

5. Can all method tests easily be performed automatically?o If not, give an example of a method signature that cannot be easily tested

directly.

6.4 Modularization and interfaces

interface - The point of connection between two modules, generally through methods.

A calculator can be divided into two parts:

user interface for the buttons and display calculation engine for the computation

The interface to a simplified calculation engine consists of methods with the signatures of:

public void plus(); 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-engine2. Create a CalcEngineTester object.

o Call the testAll() method.o Do you trust the printed results?o Call the testAll() method again.o Do you now trust the printed results?

3. The method at right tests the plus() method.o Change to test 32 + 4 =o engine is a CalcEngine field of

CalcEngineTester.o Call the testPlus() method at least

twice.

 public int testPlus() {          // Make sure the engine is in a valid starting state.    engine.clear();         // Simulate the presses: 3 + 4 =    engine.numberPressed(3);    engine.plus();    engine.numberPressed(4);    engine.equals();          // Return the result, which should be 7.    return engine.getDisplayValue(); }

Page 91

Page 92: Chapter Complete

o Do you trust the results?

 

Exercise 6 - Modularization and interfaces

In BlueJ

1. The method at right tests the minus() method.

o Change to test 32 - 4 =o Call the testMinus() method at least

twice.o Do you trust the results of minus()?

  public int testMinus() {          // Make sure the engine is in a valid starting state.     engine.clear();          // Simulate the presses: 9 - 4 =     engine.numberPressed(9);     engine.minus();     engine.numberPressed(4);     engine.equals();          // Return the result, which should be 5.     return engine.getDisplayValue(); }

6.6 Commenting and style

Exercise 7 - Commenting and style

In BlueJ

1. Open CalcEngine class.

2. Do the comments seem sufficient to explain the class and method use?

3. Is the source code layout reasonably consistent to the eye?o Indentation.o Use of { and }.o Commenting consistent.

4. Click the Implementation button and change to Interface to display the class documentation from the comments.

o Is the documentation sufficient to use the CalcEngine class without reading the source code?

6.7 Manual walkthroughs

Public manual walkthroughs share program analysis with others. Though time consuming, it is an important tool for analyzing code that fails for undetermined reasons or for code that cannot be live tested (e.g. controlling an emergency in a nuclear reactor).

Page 92

Page 93: Chapter Complete

Essentially the code in question is discussed and hand executed. You may have already done this with others on homework assignments then you know that it helps.

Exercise 8 - Manual walkthroughs to find errors

In BlueJ

1. Create a CalcEngineTester object.2. Call the testMinus() method at least twice. Note that the results differ between the first

and second calls.3. Knowing that the first call works correctly with input of:

o 9 - 4 =

Let's assume that we've determined that after the first call the CalcEngine object has the following state:

o previousOperator = '-'leftOperand = 0displayValue = 5

The second call fails with input of:

o 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:

o previousOperator = '-'leftOperand = 0displayValue = 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:

o leftOperand -= displayValue

which is:

Page 93

Page 94: Chapter Complete

o leftOperand = leftOperand - displayValue or 0 - 9 = -96. When the number 4 and '=' is entered, the equals() method at line 7 is called. The object

state is:o previousOperator = '-'

leftOperand = -9displayValue = 4

and the statement executed is line 12:

displayValue = leftOperand - displayValue or -9 - 4 = -13

7. We found the problem.o leftOperand = -9

when it should be:

o leftOperand = 9

Retracing our steps (something a debugger normally doesn't do) we may notice applyPreviousOperator() with previousOperator = '-'  is the trouble point, in line 20. In fact line 22 should have been executed instead:

o leftOperand = displayValue = 98. We may realize that the real problem is that after the '=' was entered in 9 - 4 =,

previousOperator = ' ' rather than previousOperator = '-'.

Adding the following after line 13 solves the problem:

previousOperator = ' '

1.  public void minus()2. {3.    applyPreviousOperator();4.    previousOperator = '-';5.    displayValue = 0;6. }

7. public void equals()8. {9.    if(previousOperator == '+')10.       displayValue = leftOperand + displayValue;11.    else12.       displayValue = leftOperand - displayValue;13.    leftOperand = 0;14. }

Page 94

Page 95: Chapter Complete

15. private void applyPreviousOperator()16. {17.    if(previousOperator == '+')18.       leftOperand += displayValue;19.    else if(previousOperator == '-')20.              leftOperand -= displayValue;21.           else22.             leftOperand = displayValue;23. }

6.8 Print statements

Printing the state of an object (fields), parameters and local variables as a program executes has several advantages over debugging and walkthroughs.

The following includes printing of all fields on entry and exit of the minus() method. The results of calling testMinus() twice is listed below.

1. public class CalcEngine2. {3.   private int displayValue;4.   private char previousOperator;5.   private int leftOperand;

6.   public void minus()7.   {8.      printState( "minus() entry");9.      applyPreviousOperator();10.      previousOperator = '-';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. }

minus() entry: previousOperator= displayValue=9 leftOperand=0 minus() exit:   previousOperator=- displayValue=0 leftOperand=9 minus() entry: previousOperator=- displayValue=9 leftOperand=0 minus() exit:   previousOperator=- displayValue=0 leftOperand=-9

6.8.1 Turning debugging on and off

Software development ideally is a cycle of:

Page 95

Page 96: Chapter Complete

1. Analysis to determine an appropriate solution 2. Designing a solution 3. Coding the solution 4. Testing to verify correctness 5. Use of production system 6. Maintenance by modifying, correcting, improving.

Testing and maintenance both benefit from printing debugging information while the program is running. In the production system, such debugging information should be turned off. Because most successful systems move often between testing, production and maintenance, debugging should be easily turned on and off.

The following uses the value of the field debugging=true to turn printing On. Change debugging=false to turn printing Off.

1. public class CalcEngine2. {3.   private int displayValue;4.   private char previousOperator;5.   private int leftOperand;6.   private boolean debugging = true;

7.   public void minus()8.   {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 96

Page 97: Chapter Complete

Chapter 7Designing Classes

 

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 o difficult to implement o difficult to test o difficult to get to work correctly o difficult to change

7.2 The world-of-zuul game example

Exercise 1 - zuul-bad

In BlueJ

19574779 r

ALL 0

Search site

Page 97

Page 98: Chapter Complete

1. Open project chapter07\zuul-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?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:

    NW     E    SExercise 2 - zuul-bad

In BlueJ

1. From the class diagram above, open in the editor the class Room.o Change from Implementation to Interface.o According to your map, how were the outside Room exits defined?

2. Open in the editor class Game.o Change to Implementation .o Examine the createRooms() method.o What is the effect of:

          lab.setExits(outside, office, null, null);o Finish your map.

7.3 Introduction to coupling and cohesion

cohesion - A measure of the unity of concept exhibited by methods and classes. For example, the Room class has high cohesiveness because all methods are related to the room concept.

 

Page 98

Page 99: Chapter Complete

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.o Locate the duplication.o How can the duplication be eliminated?o Remove the duplication.o Test.

 private void printWelcome(){   System.out.println();   System.out.println("Welcome to Adventure!");   System.out.println("Adventure is a ....");   System.out.println("Type 'help' if you need help.");   System.out.println();   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();}

private void goRoom(Command command) {   if(!command.hasSecondWord()) {      System.out.println("Go where?");      return;   }

   String direction = command.getSecondWord();

   // Try to leave current room.   Room nextRoom = null;   if(direction.equals("north"))      nextRoom = currentRoom.northExit;   if(direction.equals("east"))      nextRoom = currentRoom.eastExit;   if(direction.equals("south"))      nextRoom = currentRoom.southExit;   if(direction.equals("west"))      nextRoom = currentRoom.westExit;

   if (nextRoom == null)      System.out.println("There is no door!");   else {      currentRoom = nextRoom;      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 ");

Page 99

Page 100: Chapter Complete

      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 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{    private Room currentRoom;

private void printLocationInfo(){   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 ");

private void goRoom(Command command) {   String direction = command.getSecondWord();

   Room nextRoom = null;   if(direction.equals("north"))      nextRoom = currentRoom.northExit;   if(direction.equals("east"))      nextRoom = currentRoom.eastExit;   if(direction.equals("south"))      nextRoom = currentRoom.southExit;   if(direction.equals("west"))

class Room {  public Room northExit;  public Room southExit;  public Room eastExit;  public Room westExit;

  public void setExits(Room north,                                Room east,                                Room south,                                Room west)

Page 100

Page 101: Chapter Complete

   if(currentRoom.westExit != null)      System.out.print("west ");   System.out.println();}

      nextRoom = currentRoom.westExit;

   if (nextRoom == null)      System.out.println("There is no door!");   else {      currentRoom = nextRoom;      printLocationInfo()   }}

  {      if(north != null)            northExit = north;      if(east != null)            eastExit = east;      if(south != null)            southExit = south;      if(west != null)            westExit = west;  }

Exercise 4 - Encapsulation and coupling

In BlueJ

1. Edit the Room class.o Change field access from public to private.o 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  westoutside.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.

2. What is returned by:

outside.getExit("west");

lab.getExit("west");

Several iterations of getExit() method - The following represents a iterative development of a design to achieve a more extensible

Page 101

Page 102: Chapter Complete

design. The //1 design is the crudest, //2 represents some improvement and //3 represents the best design.

//1 implements the getExit() accessor method but requires adding more fields for each new direction and new if statements to setExits and getExit methods.

//2 uses a HashMap to avoid the need for multiple if statements in getExit() but setExits only allows four directions without changing the signature and adding a new field and if statements for each new direction.

//3 eliminates the need for any additional field or if statements. New directions can be added without 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

class Room {  private Room northExit;  private Room southExit;  private Room eastExit;  private Room westExit;

  public void setExits(Room north,                                Room east,                                Room south,                                Room west)  {      if(north != null)           northExit = north;      if(east != null)            eastExit = east;      if(south != null)            southExit = south;      if(west != null)            westExit = west;

// 2

class Room {  private HashMap exits;

  public void setExits(Room north,                                Room east,                                Room south,                                Room west)  {      if(north != null)            exits.put("north", north);      if(east != null)            exits.put("east", east);      if(south != null)            exits.put("south", south);      if(west != null)            exits.put("west", west); }

 public Room getExit(String

// 3

class Room { private HashMap exits;

 public void setExit(String direction,                             Room neighbor)  {    exits.put(direction, neighbor); }

 public Room getExit(String direction)  {   return (Room) exits.get(direction); }

Page 102

Page 103: Chapter Complete

 }

 public Room getExit(String direction)  {      if(direction.equals("north")         return northExit;      if(direction.equals("east")         return eastExit;      if(direction.equals("south")         return southExit;      if(direction.equals("west")         return westExit; }

direction)  {    return (Room)exits.get(direction); }

 

Exercise 5 - Decoupling

In BlueJay

1. Copy and paste the full version of the decoupled Room class // 3 below.o Compile Room and Game classes.

// 3import java.util.HashMap;

class Room {  private String description;  private String exitString;  private HashMap exits;

 public Room(String description)  {    this.description = description;    exitString = "";    exits = new HashMap(); }

 public void setExit(String direction,                             Room neighbor)  {    exits.put(direction, neighbor);    exitString = exitString + " " + direction; }

 public Room getExit(String direction)  {   return (Room) exits.get(direction); }

Page 103

Page 104: Chapter Complete

 public String getDescription() {   return description; }

  public String getExitString() {   return exitString; }}

2. Compiling Game class should give errors resulting from our decoupling changes to Room. Setting exits of the outside Room is below:

o outside.setExit("east", theatre);o outside.setExit("south", lab);o outside.setExit("west", pub);

3. Complete setting the theatre Room exits and comment out setting the remaining Room exits for now.

o Compile Game, more errors.

 

Exercise 6 - Decoupling

In BlueJ

1. Compile Game, more errors.o We have eliminated northExit, etc. in favor of the getExit() accessor method of

Room.o 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:

o if(direction.equals("north"))      nextRoom = currentRoom.northExit;

3. Make the changes to the goRoom() method of Game.4. Compile Game.

private void goRoom(Command command)

Page 104

Page 105: Chapter Complete

{   String direction = command.getSecondWord();

   Room nextRoom = null;   if(direction.equals("north"))      nextRoom = currentRoom.northExit;   if(direction.equals("east"))      nextRoom = currentRoom.eastExit;   if(direction.equals("south"))      nextRoom = currentRoom.southExit;   if(direction.equals("west"))      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.o 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.

o An accessor method getExitString() returns the String field exitString.o For example:

outside.getExitString() returns "east south west".

o The changes have been made to Room class. Examine.

Page 105

Page 106: Chapter Complete

4. What are the changes to use getExitString() rather than northExit in:

o    if(currentRoom.northExit != null)      System.out.print("north ");

5. Make the changes to the printLocationInfo() method below (i.e. your method created to remove the duplication) of Game.

6. Compile Game. Does that resolve the explicit coupling errors?

private void printLocationInfo(){   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.  

Changing internal data has no effect as long as method interfaces remain the same. 

Other classes with access are tightly coupled, need insider knowledge of the data. 

Changing internal data can require changing other classes with access to the data.

Page 106

Page 107: Chapter Complete

Adding other directions has been made simple through our earlier exercises. But suppose we want to place treasure, weapons or monsters in the rooms and be able to add or remove items as the game progresses. 

Exercise 8 - Responsibilities

The current definition of printLocationInfo() would need to be changed if Room added other information to be printed. For the Room class to be responsible for its own data, it should return a full description of the 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.

2. Make changes needed to printLocationInfo() method (i.e. your method created to remove the duplication) of Game.

class Room{   public String getLongDescription()  {      return "You are " + description + ".\n" +                getExitString();  }

7.8 Localizing change

localizing change - Changing one class should only minimally effect other classes. Promoted by loose coupling and high cohesion. Design classes with modification and extension in mind.

7.9 Implicit coupling

implicit coupling - Coupling that may not produce a syntax error when changes occur.

Use of public fields has obvious potential for tight coupling that leads to syntax errors when fields change in some way. Implicit coupling is often due to duplication of data throughout the application. Data should occur only once in an application.

The game commands are:

go

Page 107

Page 108: Chapter Complete

help quit

The data for recognizing commands in the CommandWords class with "look" added is:

class CommandWords{   private static final String 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 Game{ private Parser parser;

 private void printHelp() {  System.out.println(                 "You are lost.");  System.out.println(                 "Your command words are:");  System.out.println(                 parser.getCommands());

class Parser{ private CommandWords                            commands;

 public String getCommands() {    return        commands.getWords(); }

class CommandWords{ private static final String   validCommands[] =     { "go", "quit", "help", "look" };

 public String getWords()  {  String words = "";  for(int i=0; i<validCommands.length; i++)              words = words + " " +                                     validCommands[i];

Page 108

Page 109: Chapter Complete

}  return words; }

 

Exercise 9

Examine the following Game method. Does implicit coupling still exist with CommandWords class?

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; }

7.10 Thinking ahead

The Game class is responsible for interacting with the user including all input and printing to the terminal.

Other classes maintain data. Changing from a terminal to a graphical interface is therefore much easier because the

input to manipulate and display the game state is confined to the Game class.

Model/View/Controller - models for maintaining data, views for displaying the data, and controllers for manipulating the model.

Model: Classes are responsible for the model data. When significant changes occur in the model, the application updates all of its views. The Room class is responsible for Room data, the Parser for Parser data, etc.

Page 109

Page 110: Chapter Complete

View: The user interface to display the model. Objects must register with the model to receive updates when the model changes. The Game class displays the Game model, the Room class displays (through getExitString() ) Room model, etc.

Controller: The user interface to manipulate the model data. The Game class reads user commands from the keyboard, the Room model data is manipulated through methods (e.g. setExit()).

7.11 Cohesion

7.11.1 Cohesion of methods

method cohesion - A cohesive method is responsible for only one task.

 

class Game{  public void play()   {      System.out.println();     System.out.println("Welcome to Adventure!");     System.out.println("Adventure is a new, incredibly boring adventure game.");     System.out.println("Type 'help' if you need help.");     System.out.println();     printLocationInfo();

     currentRoom = outside;

     boolean finished = false;     while (! finished) {          Command command = parser.getCommand();          finished = processCommand(command);     }     System.out.println("Thank you for playing. Good bye.");  }}Exercise 10 - Cohesion of methods

Is the above play() method cohesive? Are there any changes that would make it more cohesive?

7.11.2 Cohesion of classes

class cohesion - A cohesive class is responsible for one thing.

Room class is cohesive because it is responsible only for the state of a room. Only methods to manipulate (mutator) or view (accessor) room data are provided by the Room class.

Page 110

Page 111: Chapter Complete

Parser class is cohesive because it is only responsible for commands. The getCommands() method added to return the list of valid commands did not reduce cohesion because the commands are part of the responsibility of a Parser.

Exercise 11 - Cohesion of classes

1. Is our text book more or less cohesive than the National Inquirer?2. Would adding a text chapter about a meeting between space aliens and George Bush

produce more or less cohesion?3. Would adding a Parser class method to manipulate the Room state or adding a Room

field to the Parser:a. Add an arrow from Room to Parser in the class diagram?b. Increase or decrease coupling between Parser and Room classes?c. Increase or decrease class cohesion of Parser?d. Increase or decrease class cohesion of Room?

7.11.3 Cohesion for readability

Class cohesion essentially groups common data and methods into a class. Reading and understanding one independent class is generally much easier than understanding many tightly coupled classes.

Exercise 12 - Cohesion for readability

1. How are the Parser and Room classes coupled? Loosely, tightly or not at all?2. Would it make sense to read the Parser class to understand the Room class?

7.11.4 Cohesion for reuse

reuse - Multiple use of the same class or method (i.e. calling the method more than once)..

Reuse is enhanced by strong cohesion. Generally a method that performs a simple operation is more reusable than one that

produces a complex result.

class Game{  private void printWelcome() {    System.out.println("Welcome to Adventure!");    System.out.println("Type 'help' if you need help.");    System.out.println();    System.out.println(currentRoom.getLongDescription());  }

  private void goRoom(Command command)   {     if (nextRoom == null)        System.out.println("There is no door!");    else {

Page 111

Page 112: Chapter Complete

        currentRoom = nextRoom;        System.out.println(currentRoom.getLongDescription());    }  }}

 

Exercise 13 - Cohesion for reuse

What is reused in the above fragment?

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.

Exercise 14 - Refactoring

Add items (money, monsters, etc.) of varying weights placed in rooms.

1. What data (fields) is needed for an item?

2. What methods are needed to manipulate the fields?

3. Where are the most obvious points for refactoring to have different items in a room?o Will the Room class need refactoring?o Will Game class need refactoring?o Should a new Item class be defined with responsibility for the items?

7.12.1 Refactoring and testing

Because refactoring changes classes and methods, tests must change also.

Exercise 15 - Refactoring and testing

Does a class that tests other classes need to be refactored when:o additional methods are added to classes tested?o methods are removed from classes?o signatures of methods tested change?o signatures of methods tested do not change?

7.12.2 An example of refactoring

Page 112

Page 113: Chapter Complete

Exercise 16 - Refactoring example

Add ability for the player to pick up and put down items found in rooms.

1. What actions (methods) are needed to manipulate item?

2. Should an Item pick itself up or should a player pick up an Item?

3. Should the Item class have responsibility that includes a player carrying an item?

4. Rate the following from most (1) to least (5) appropriate:a. Room class is refactored with responsibility that includes items a player is

carrying.b. Game class is refactored with responsibility that includes items a player is

carrying.c. Item class is refactored with responsibility that includes a player carrying an

item.d. Player class is created with responsibility that includes items a player is

carrying.e. Parser class is refactored with responsibility that includes items a player is

carrying.

5. Will Game class need refactoring?

7.13 Design guidelines

7.14 Executing without BlueJ

7.14.1 Class methods

instance method - Methods invoked on an instance (object) of a class.class method - Methods invoked on the class.

Class methods must be static since no instance (object) used to invoke the method. For example, the following invokes the Math class method sqrt :

o Math.sqrt(16.0) returns 4.0

7.14.2 The main method

Running without BlueJ requires adding a main() method. For the Game() class, the following creates a new Game instance and calls the play()

method.

class Game{   public static void main(String args[])   {      ( new Game() ).play();  }}

Page 113

Page 114: Chapter Complete

IUS - The Game class method can be executed by: o Start | Programs | Accessories | Command Prompt o Change to the directory containing the Java Game class files.

H: cd c201\projects\chapter07\zuul-better v:\common\user\b438\forjava java -cp . Game

7.14.3 Limitations of class methods

Class method cannot access instance fields. Makes sense because no instance (object) was used to invoke the class method so no instance fields exist.

Class method cannot call an instance method for reason that no instance exists. Can only call other class methods.

Chapter 8Improving structure with inheritance

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.  

private - Subclasses inherit but cannot access private methods or fields.

public - TicketMachine methods that are public can be called as internal methods (i.e. called on a BusTicketMachine object). Public fields are accessible in subclass.

constructor - TicketMachine constructors can be called as super followed by any normal parameters. The TicketMachine(int ticketCost) constructor is called by super(cost) in the

19574779 r

ALL 0

Search site

Page 114

Page 115: Chapter Complete

BusTicketMachine( int cost, String bus, String stops ) constructor below. 

over-riding methods - The printTicket() method is defined in both classes, the definition used is the closest class.  BusTicketMachine objects call BusTicketMachine printTicket() method, TicketMachine objects call TicketMachine printTicket() method. 

super - Over-riding methods as with printTicket() blocks access to inherited methods. To call a super class method, precede the method call with super.

1.  public class TicketMachine2.  {3.     private int price;4.     private int balance;5.     private int total; 

6.     public TicketMachine(int ticketCost)

7.    {8.        price = ticketCost;9.        balance = 0;10.        total = 0;11.     }

12.    public void insertMoney(int amount)

13.    {14.        balance += amount;15.    }

16.    public void printTicket()17.    {18.        System.out.println("# " + price +

                                  " cents.");19.        total += balance;20.        balance = 0;21.    }22. }

23. public class BusTicketMachine extends TicketMachine

24. {25.     private String bus, stops;

26.     public BusTicketMachine( int theCost, String theBus,                                        String theStops )

27.     {28.           super( theCost );29.           bus = theBus;30.           stops = theStops;31.      }

32.      public void printStops()33.      {34.          System.out.println("# Bus " + bus );35.          System.out.println("# Stops " +

stops );36.      } 

37.      public void printTicket()38.      {39.          System.out.println("# Ticket for bus  "

+ bus );40.          super.printTicket();41.      }42. }

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.

Trace the execution of:

btm.insertMoney( 75 );

Page 115

Page 116: Chapter Complete

Trace the execution of:

btm.printTicket( );

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.  

The class fields are listed in the object diagram for each at right.

Exercise 2 - Need for Inheritance

How are the CD and Video fields the same?

How are the CD and Video fields different?

What types are each of the fields?

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.

Page 116

Page 117: Chapter Complete

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

The database holds the CD and Video collections separately as an ArrayList object for each.

The object diagram of the

database coarsely illustrates the database object with four CDs and four Videos.

 

 

8.1.2 DoME source code

Exercise 3 - Need for Inheritance

1. How are CD and Video methods the same?

2. How are CD and Video fields the same?

3. How are the CD and Video methods different?

4. How are the CD and Video fields different?

 

public class Video {   private String title;   private String director;   private int playingTime;   private boolean gotIt;   private String comment;

public class CD{   private String title;   private String artist;   private int numberOfTracks;   private int playingTime;   private boolean gotIt;

Page 117

Page 118: Chapter Complete

   public Video(String theTitle, String theDirector,                      int time)   {      title = theTitle;      director = theDirector;      playingTime = time;      gotIt = false;      comment = "<no comment>";   }

   public void setComment(String comment)   {     this.comment = comment;   }

   public String getComment()   {      return comment;   }

   public void setOwn(boolean ownIt)   {      gotIt = ownIt;  }

   public boolean getOwn()   {      return gotIt;   }

   public void print()   {      System.out.print("video: " + title +                                 " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + director);      System.out.println(" " + comment);   }}

   private String comment;

   public CD(String theTitle, String theArtist, int tracks,                  int time)   {      title = theTitle;      artist = theArtist;      numberOfTracks = tracks;      playingTime = time;      gotIt = false;      comment = "<no comment>";   }

   public void setComment(String comment)   {    this.comment = comment; }

   public String getComment()   {    return comment; }

   public void setOwn(boolean ownIt)   {    gotIt = ownIt; }

   public boolean getOwn()   {    return gotIt; }

   public void print()   {      System.out.print("CD: " + title +                                  " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + artist);      System.out.println(" tracks: " + numberOfTracks);      System.out.println(" " + comment);   }}

Database class

The database values are not stored on a file so are lost when program closed. There is no user interface except using BlueJ.

import java.util.ArrayList;import java.util.Iterator;

public class Database{

Exercise 3.5 - Need for Inheritance

1. What fields are similar?

Page 118

Page 119: Chapter Complete

   private ArrayList cds;   private ArrayList videos;

   public Database()   {      cds = new ArrayList();      videos = new ArrayList();   }

   public void addCD(CD theCD)   {   cds.add(theCD);   }

   public void addVideo(Video theVideo)   {   videos.add(theVideo);   }

   public void list()   {      // print list of CDs      for(Iterator iter = cds.iterator(); iter.hasNext(); ) {         CD cd = (CD)iter.next();         cd.print();         System.out.println(); // empty line between items      }

      // print list of videos      for(Iterator iter = videos.iterator(); iter.hasNext(); ) {         Video video = (Video)iter.next();         video.print();         System.out.println(); // empty line between items      }   }}

2. What methods are similar

The figure at right reflects the DoME application after four CDs and four Videos have been entered into the Database object.

Exercise 4 - DoME

In BlueJ

1. Open project chapter08/dome-v1

2. Create one CD and Video objects.

3. Create one Database object.

Page 119

Page 120: Chapter Complete

4. Enter the CD and Video objects into the Database object.5. List the database contents.

o Do any objects have comments?6. Add a comment to one of the Video objects.7. List the database contents.

o Can you explain the printed output by the figure at right and examining CD and Video print() methods below?

public class Video {

   public void print()   {      System.out.print("video: " + title +                                 " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + director);      System.out.println(" " + comment);   }

public class CD{

   public void print()   {      System.out.print("CD: " + title +                                  " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + artist);      System.out.println(" tracks: " + numberOfTracks);      System.out.println(" " + comment);   }}

8.2 Using inheritance

inheritance - defines one class as an extension on another.

 

Item class defines those fields and methods duplicated or common to both CD and Video class.  

o The Item methods are defined public, can be inherited by the modified CD and Video class, and can be called from the CD or Video class. 

o The Item fields are private, are inherited but cannot be accessed from the CD or Video class. 

o Three methods, getArtist and getNumberOfTracks in CD and getDirector in Video have been added.  

Page 120

Page 121: Chapter Complete

Item class code

public class Item{   private String title;   private int playingTime;   private boolean gotIt;   private String comment;

   public Item(String theTitle, int time)   {      title = theTitle;      playingTime = time;      gotIt = false;      comment = "";   }

   public void setComment(String comment)   {    this.comment = comment; }

   public String getComment()   {    return comment; }

   public void setOwn(boolean ownIt)   {    gotIt = ownIt; }

   public boolean getOwn()   {    return gotIt; }

   public void print()   {      System.out.print("title: " + title + " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + comment);   }}

CD class code

Before inheritance After inheritance

public class CD{   private String title;   private String artist;   private int numberOfTracks;

public class CD extends Item{   private String artist;   private int numberOfTracks;

Page 121

Page 122: Chapter Complete

   private int playingTime;   private boolean gotIt;   private String comment;

   public CD(String theTitle, String theArtist,                  int tracks, int time)   {      title = theTitle;      artist = theArtist;      numberOfTracks = tracks;      playingTime = time;      gotIt = false;      comment = "<no comment>";   }

   public void setComment(String comment)   {    this.comment = comment; }

   public String getComment()   {    return comment; }

   public void setOwn(boolean ownIt)   {    gotIt = ownIt; }

   public boolean getOwn()   {    return gotIt; }

   public void print()   {      System.out.print("CD: " + title +                               " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + artist);      System.out.println(" tracks: " + numberOfTracks);      System.out.println(" " + comment);   }}

   public CD(String theTitle, String theArtist,                  int tracks, int time)   {      super(theTitle, time);      artist = theArtist;      numberOfTracks = tracks;   }

   public String getArtist()   {   return artist;   }

   public int getNumberOfTracks()   {   return numberOfTracks;   }

   public void print()   {      System.out.println(" " + artist);      System.out.println(" tracks: " + numberOfTracks);   }}

Video class code

Before inheritance After inheritance

public class Video {

public class Video extends Item {

Page 122

Page 123: Chapter Complete

   private String title;   private String director;   private int playingTime;   private boolean gotIt;   private String comment;

   public Video(String theTitle, String theDirector,                      int time)   {      title = theTitle;      director = theDirector;      playingTime = time;      gotIt = false;      comment = "<no comment>";   }

   public void setComment(String comment)   {     this.comment = comment;   }

   public String getComment()   {      return comment;   }

   public void setOwn(boolean ownIt)   {      gotIt = ownIt;  }

   public boolean getOwn()   {      return gotIt;   }

   public void print()   {      System.out.print("video: " + title +                                 " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + director);      System.out.println(" " + comment);   }}

   private String director;

   public Video(String theTitle, String theDirector,                     int time)   {      super(theTitle, time);      director = theDirector;   }

   public String getDirector()   {   return director;   }

   public void print()   {      System.out.println(" " + director);   }

}

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.

Page 123

Page 124: Chapter Complete

2. Extend the hierarchy diagram at right to include musicals, science fiction, soap operas, TV shows and comedy.

8.4 Inheritance in Java

Item is the parent or super class. Video and CD class

o Child or subclasses, inheriting from Item. o Have methods and fields of super class Item. o Can call public Item methods as internal methods. o Cannot access private fields even though inherited.

Item Video CD

public class Item{ private String title; private int playingTime; private boolean gotIt; private String comment;

 public Item(String theTitle, int time)

 public void setComment(String comment)

 public String getComment()

 public void setOwn(boolean ownIt)  public boolean getOwn()

 public void

public class Video extends Item{ private String director;

 public void print() {   System.out.println(" " + director); }

 public String getDirector() {   return director;   }

}

public class CD extends Item{ private String artist; private int numberOfTracks;

 public void print() {   System.out.println(" " + artist);   System.out.println(" tracks: " +             numberOfTracks); }

  public String getArtist()  {   return artist;   }

   public int getNumberOfTracks()   {   return numberOfT

Page 124

Page 125: Chapter Complete

print()racks;   }}

8.4.1 Inheritance and access rights

Exercise 6 - Inheritance and access rights

In BlueJ

1. Open project Chapter08/dome-v2

2. Create a CD object.o Call a public inherited

method such as setComment().

3. Open class Video4. Remove the extends Item

o What is the result of compiling Video?

o Why?5. Restore the extends Item

8.4.2 Inheritance and initialization

Superclass constructor - Subclass constructor must call super-class constructor as the first statement.

Constructors initialize object fields. Subclass must call super-class constructor to initialize inherited fields.

Item Video CD

1. public class Item2. {3.    private String title;4.    private int

playingTime;5.    private boolean

gotIt;6.    private String

comment;

7.    public Item(String theTitle,                          int time)

14. public class Video extends Item

15. {16.     private String

director;

17.     public Video(String theTitle,                       String theDirector,                       int time)

18.    {19.       super(theTitle,

time);20.       director =

22. public class CD extends Item

23. {24.    private String artist;25.    private int

numberOfTracks;

26.    public CD(String theTitle,                   String theArtist,                   int tracks,                   int time)

27.    {28.       super(theTitle,

Page 125

Page 126: Chapter Complete

8.    {9.       title = theTitle;10.       playingTime =

time;11.       gotIt = false;12.       comment = "";13.    }

theDirector;21.    }

time);29.       artist = theArtist;30.       numberOfTracks =

tracks;31.    }

Exercise 7 - Inheritance and initialization

In your head

1. Trace the execution of:o CD mycd = new

CD("Quacker", "Duck", 300, 10000);

2. Trace the execution of:o 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.o Inspect.o Step Into to step through

the execution.o What constructor was

executed for super()?o Are Item fields part of the

CD object in the Inspector?

One Two Three1. public class

One2. {3.    private

String oneS;

4.    public One(String theS)

5.    {6.       oneS =

theS;7.    }

8.    public String getOneS()

13. public class Two extends One

14. {15.     private String twoS;

16.     public Two(String theS)

17.    {18.       super("red");19.       twoS = theS;20.    }

21.    public String getTwoS()

22.    {23.        return twoS;

26. public class Three extends Two27. {28.    private String threeS;

29.    public Three(String theS)30.    {31.       super("blue");32.       threeS = theS;33.    }

34.    public String getThreeS()35.    {36.        return threeS;37.    }38. }

Page 126

Page 127: Chapter Complete

9.    {10.        return

oneS;11.    }12. }

24.    }25. }

Exercise 7.1 - Inheritance and initialization

In your head

1. For the Java code above, draw the UML class diagram similar to at right that shows inheritance of fields and methods.

2. Trace the execution of:o One myOne = new

myOne("white");o System.out.print( myOne.g

etOneS() );

3. Trace the execution of:o Two myTwo = new

myTwo("red");o System.out.print( myTwo.g

etTwoS() );

4. Trace the execution of:o Three myThree = new

myThree("blue");o System.out.print( myThree

.getThreeS() );

8.5 DoME: adding other item types

reuse - Using existing classes in a new context.

Exercise 8 - Reuse

In BlueJ

1. Add the following constructor with no parameters to Item:

o public Item () { }2. Create a class Game that inherits from

Item.o Game class has no fields,

constructors or methods.

Page 127

Page 128: Chapter Complete

3. Create a class VideoGame that inherits from Game.o VideoGame class has no fields, constructors or methods.

4. Examine the class diagram.o What class or classes are inherited by VideoGame?

8.6 Advantages of inheritance (so far)

Avoids duplication of code that is inherited (e.g. CD, Video, Game and VideoGame use same code from Item).

Reuse of inherited code by multiple subclasses. Maintenance easier since inherited code shared by subclasses, changes in parent class

automatically extended to subclasses. Extensibility from parent class to more specific subclasses.

8.7 Subtyping

Database class is simplified because now only responsible for Items, includes CDs and Videos through inheritance.

Only one ArrayList that references both CDs and Videos. Only one addItem() method for both CDs and Videos. Only one list() method for both CDs and Videos. CDs and Videos both Items through inheritance. Database need only handle Items to handle any subclass of Item.

Without Inheritance With Inheritance

import java.util.ArrayList;import java.util.Iterator;

public class Database{   private ArrayList cds;   private ArrayList videos;

   public Database()   {      cds = new ArrayList();      videos = new ArrayList();   }   public void addCD(CD theCD)   {   cds.add(theCD);   }

   public void addVideo(Video theVideo)   {   videos.add(theVideo);   }

import java.util.ArrayList;import java.util.Iterator;

public class Database{   private ArrayList items;

   public Database()   {      items = new ArrayList();   }

   public void addItem(Item theItem)   {      items.add(theItem);     }

Page 128

Page 129: Chapter Complete

   public void list()   {      // print list of CDs      for(Iterator iter = cds.iterator(); iter.hasNext(); ) {         CD cd = (CD)iter.next();         cd.print();         System.out.println(); // empty line between items      }

      // print list of videos      for(Iterator iter = videos.iterator(); iter.hasNext(); )      {         Video video = (Video) iter.next();         video.print();         System.out.println(); // empty line between items      }   }}

   public void list()   {      for(Iterator iter = items.iterator(); iter.hasNext(); )      {         Item item = (Item) iter.next();         item.print();      }   }}

Exercise 8.2 - Subtyping

In BlueJ

1. Open chapter08/dome-v2.2. Create Database, Video and CD objects.3. Add each Item to the database.4. List the database.

8.7.1 Subclasses and subtypes

Primitive type - Non-object types such as int, boolean, char, double.

Object type - Defined by classes.

Subtype - Defined by subclass hierarchy.

A CD object is of type CD, CD is a subtype of Item. A VideoGame object is of type VideoGame.

Page 129

Page 130: Chapter Complete

VideoGame is a subtype of Game. Game is a subtype of Item.

8.7.2 Subtyping and assignment

The two following definitions are compatible.

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.

Item item1 = new Item();Game game1 = new Game();VideoGame vg1 = new VideoGame();

Game variable game1 can reference Game or VideoGame objects (same type or subtype) but not Item.  

Item variable item1 can reference Item objects and CD, Video, Game or VideoGame objects. 

VideoGame variable vg1 can reference VideoGame objects but not Game or Item.

Compatible Types Incompatible Types

item1 = game1;  game1 = vg1;

Item item2 = new Game();Game game2 = new VideoGame();

game1 = item1;vg1 = game1;vg1 = item1;

VideoGame vg2 = new Game();Game game2 = new 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.

Exercise 9 - Subtyping and

Page 130

Page 131: Chapter Complete

assignments

Which statements are true?

1. Game is a subclass of Item.2. Game is a superclass of VideoGame.3. Game is a subclass of Video.4. Game is a superclass of Video.

Item item1 = new Item();Game game1 = new Game();VideoGame vg1 = new VideoGame();

Which are valid (using above item1, game1 and vg1 definitions)?

1. item1 = game1;2. game1 = item1;3. game1 = vg1;4. vg1 = item1;5. Item item2 = new Game();6. Game game2 = new Item();7. Video video1 = new Game();

One Two Three1. public class

One2. {3.    private

String oneS;

4.    public One(String theS)

5.    {6.       oneS =

theS;7.    }

8. public class Two extends One9. {10.     private String twoS;

11.     public Two(String theS)12.    {13.       super("red");14.       twoS = theS;15.    }

16. public class Three extends Two

17. {18.    private String threeS;

19.    public Three(String theS)

20.    {21.       super("blue");22.       threeS = theS;23.    }

Exercise 9.1 - Subtyping and assignments

Give the inheritance hierarchy diagram for the above classes.

Which are valid using the myOne, myTwo and myThree definitions?

One    myOne;Two    myTwo;Three  myThree;

1. myOne = myTwo;2. myOne = myThree;3. myThree = myTwo;4. myThree = myOne;

Page 131

Page 132: Chapter Complete

5. myOne = new Two("purple");6. myTwo = new One("green");7. myThree = new Two("orange");

8.7.3 Subtyping and parameter passing

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.

public class Database{    public void addItem( Item theItem ) {}    public void addGame( Game theGame ) {}    public void addVideoGame( VideoGame theVidoGame ) {}}

    Database db = new Database();    Item item1 = new Item();    Game game1 = new Game();    VideoGame vg1 = new VideoGame();

Compatible Incompatible

db.addItem( item1 );db.addItem( game1 );db.addItem( vd1 );db.addGame( vd1 );db.addVideoGame( vd1 );

db.addGame( item1 );db.addVideoGame( item1 );db.addVideoGame( game1 );

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.

Exercise 10 - Parameter subtypes

Which are valid (using above db, item1, game1 and vg1 definitions)?

1. db.addItem(item1);2. db.addItem(game1);

Page 132

Page 133: Chapter Complete

3. db.addItem(vg1);

Which are valid (using above db, item1, game1 and vg1 definitions)?

1. db.addGame(item1);2. db.addGame(game1);3. db.addGame(vg1);4. db.addVideoGame(item1);5. db.addVideoGame(vg1);6. db.addVideoGame(game1);

8.7.4 Polymorphic variables

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.

Classes can over-ride inherited methods (i.e. methods with the same name) and variables can reference objects of a subclass. For example, the following executes the getS() method of class Two at line 16:

Two aTwo = new Two("purple");aTwo.getS();

But the following executes the getS() method of class Three at line 29:

Two aTwo = new Three("purple");aTwo.getS();

The type the object referenced is Three so the Three method was executed.

One Two Three

1. public class One2. {3.    private String

oneS;

13. public class Two extends One

14. {15.     private String twoS;

26. public class Three extends Two

27. {28.    private String threeS;

Page 133

Page 134: Chapter Complete

4.    public One(String theS)

5.    {6.       oneS = theS;7.    }

8.    public String getS()

9.    {10.        return oneS;11.    }12. }

16.     public Two(String theS)

17.    {18.       super("red");19.       twoS = theS;20.    }

21.    public String getS()22.    {23.        return twoS;24.    }25. }

29.    public Three(String theS)

30.    {31.       super("blue");32.       threeS = theS;33.    }

34.    public String getS()35.    {36.        return threeS;37.    }38. }

Exercise 11a - Polymorphism

Which are valid? Trace the execution. Note that One, Two and Three each

have a getS() method.

   One myOne     = new One("red");   Two myTwo     = new Two("white");   Three myThree = new Three("blue");

   System.out.print( myOne.getS() );   System.out.print( myTwo.getS() );   System.out.print( myThree.getS() );

Exercise 11b - Polymorphism

Which are valid? Trace the execution. Note that One, Two and Three each

have a getS() method.

   One myOne     = new Two("red");   Two myTwo     = new Three("white");   Three myThree = new One("blue");

   System.out.print( myOne.getS() );   System.out.print( myTwo.getS() );   System.out.print( myThree.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.

Without inheritance With inheritance

public class Database{   public void list()   {      // print list of CDs      for(Iterator iter = cds.iterator(); iter.hasNext(); ) {         CD cd = (CD) iter.next();         cd.print();         System.out.println(); // empty line between items      }

      // print list of videos      for(Iterator iter = videos.iterator();

public class Database{   public void list()   {      for(Iterator iter = items.iterator(); iter.hasNext(); )      {         Item item = (Item) iter.next();         item.print();      }   }

Page 134

Page 135: Chapter Complete

iter.hasNext(); ) {         Video video = (Video) iter.next();         video.print();         System.out.println(); // empty line between items      }   }

Exercise 11.2 - Polymorphism

Which are valid? Note that Item, CD and Video each have a print() method.

    Item item1 = new Item();    Video video1 = new Video();    CD cd1 = new CD();

    video1.list();    cd1.list();    item1.list();

8.8 The Object class

Object - The top-level class. All classes inherit from Object class.

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.

 

Object is the superclass of all classes. Item is a subclass of Object. The following are equivalent:

public class Item

public class Item extends Object

Exercise 12 - Object

Are the following equivalent according to the hierarchy at right?

  public class Game extends

Page 135

Page 136: Chapter Complete

Object  public class Game extends ItemWhich 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 );

8.9 Polymorphic collections

8.9.1 Element types

Polymorphic collections can reference different types of objects. The Java collections ArrayList and HashMap are examples, able to reference String, TicketMachine, Game or other objects.

This is possible because these collections are defined to reference Object types. From our rules repeated below, we know that a variable of type Object can reference an object any subtype.

ArrayList signatures are given below for the add() and get() methods. Because Object is the super-type of all types, an ArrayList element can reference any other type.

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.

Passing subtypes - Actual parameters can be passed to formal parameters of the same or supertype.

Page 136

Page 137: Chapter Complete

Passing supertypes - Actual parameters can not be passed to formal parameters of a subtype.

public class ArrayList{    public void add( Object theObject )

    public Object get( int index)

public class HashMap{    public void put( Object key, Object theObject )

    public Object get( Object key )

8.9.2 Casting revisited

Now we can understand the need for casting.

The ArrayList method get() returns a reference to an Object. Object is the superclass so cannot be assigned to a subtypes such as Item, TicketMachine, etc. It must be cast to the correct type for the assignment.

Compile errors - The compiler can detect errors where a supertype is assigned to a subtype variable in // 1 below.

Runtime errors - The compiler can not detect errors where a subtype is assigned to the incorrect type variable as in // 3 below. However, at runtime // 3 will cause the program to fail.

Why can't the compiler catch the error in // 3? Because at runtime the ArrayList element 1 could be a CD, Video or any other subtype of Object. It depends upon what we have added to the ArrayList.

ArrayList aL = new ArrayList();

aL.add( new CD() );aL.add( new Video() );

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.

Exercise 12.1 - Polymorphism

Diagram the ArrayList aL.

Page 137

Page 138: Chapter Complete

What is the hierarchy diagram classes One, Two and Three?

ArrayList aL = new ArrayList();

One aOne     = new One("red");Two aTwo     = new Two("white");Three aThree = new Three("blue");

aL.add( aOne );aL.add( aTwo );aL.add( aThree );

Which of the following are valid syntax?

a. aOne = aL.get(0);

b. aOne = (One) aL.get(0);

c. aThree = (One) aL.get(2);

d. aThree = (Three) aL.get(2);

e. aThree = (Two) aL.get(1);

f. ((Three) aL.get(2)).getS();

Which of the following give a runtime error?

a. aOne = (One) aL.get(0);

b. aThree = (Three) aL.get(2);

c. aThree = (Three) aL.get(1);

d. aTwo = (Two) aL.get(2);

e. ((Three) aL.get(2)).getS();

One Two Three

1. public class One2. {3.    private String

oneS;

4.    public One(String theS)

5.    {

13. public class Two extends One

14. {15.     private String twoS;

16.     public Two(String theS)

17.    {

26. public class Three extends One

27. {28.    private String threeS;

29.    public Three(String theS)

30.    {

Page 138

Page 139: Chapter Complete

6.       oneS = theS;7.    }

8.    public String getS()

9.    {10.        return oneS;11.    }12. }

18.       super("red");19.       twoS = theS;20.    }

21.    public String getS()22.    {23.        return twoS;24.    }25. }

31.       super("blue");32.       threeS = theS;33.    }

34.    public String getS()35.    {36.        return threeS;37.    }38. }

8.9.3 Wrapper classes

Wrapper classes - One common use is a class defined to encapsulate a primitive type for use as an object.

You may have noticed that primitive types such as int, boolean, etc. are not used in collections such as ArrayList, HashMap, etc. The reason being that collections can only reference Objects.

Java already defines wrapper classes for all primitives. For example:

Integer for int Double for double

The wrapper classes Integer and Double inherits from Object so that Integer or Double objects can be treated as normal objects while holding the value of the primitive type.

ArrayList aL = new ArrayList();Integer integer1 = new Integer( 5 );

aL.add( integer1 );aL.add( new Integer( 3 ) );

Integer integer2 = (Integer) aL.get( 0 );

int int1 =  integer2.intValue();

int int2 = ((Integer).get( 1 )).intValue();

Exercise 13 - Wrappers

What is the value of int1 and int2?

8.10 The collection hierarchy

Page 139

Page 140: Chapter Complete

Chapter 9More about inheritance

FreeFind

Modified:  08/27/2004 12:48:17

Overview

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.

19574779 r

0

Search site

Page 140

Page 141: Chapter Complete

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. 

TicketMachine tm = new BusTicketMachine( 50, "Number 3", "4th St. - Mall - Airport" );tm.printTicket();

Invokes the printTicket() method at line 37.

TicketMachine tm = new TicketMachine( 50 );tm.printTicket();

Invokes the printTicket() method at line 16.

1.  public class TicketMachine2.  {3.     private int price;4.     private int balance;5.     private int total; 

6.     public TicketMachine(int ticketCost)

7.    {8.        price = ticketCost;9.        balance = 0;10.        total = 0;11.     }

12.    public void insertMoney(int amount)

13.    {14.        balance += amount;15.    }

16.    public void printTicket()17.    {18.        System.out.println("# " + price +

                                  " cents.");

19.        total += balance;20.        balance = 0;21.    }22. }

23. public class BusTicketMachine extends TicketMachine

24. {25.     private String bus, stops;

26.     public BusTicketMachine( int theCost, String theBus,                                        String theStops )

27.     {28.           super( theCost );29.           bus = theBus;30.           stops = theStops;31.      }

32.      public void printStops()33.      {34.          System.out.println("# Bus " + bus );35.          System.out.println("# Stops " +

stops );36.      }

37.      public void printTicket()38.      {39.          System.out.println("# Ticket for bus  "

+ bus );40.          super.printTicket();41.      }42. }

Exercise 0a - Method Polymorphism

Page 141

Page 142: Chapter Complete

Suppose that we have created a BusTicketMachine by:

BusTicketMachine tm1 = new BusTicketMachine( 50, "Number 3", "4th St. - Mall - Airport" );

TicketMachine t2 = new TicketMachine( 60 );

TicketMachine t3 = new BusTicketMachine( 50, "Number 3", "4th St. - Mall - Airport" );

1. Are the following valid?

tm1.printStops();

tm2.printStops();

tm3.printStops();

2. Trace the execution of:

tm1.printTicket();

tm2.printTicket( );

tm3.printTicket( );

 

One Two Three

1. public class One2. {3.    private String

oneS;

4.    public One(String theS)

5.    {6.       oneS = theS;7.    }

8.    public String getS()

9.    {10.        return oneS;11.    }12. }

13. public class Two extends One

14. {15.     private String twoS;

16.     public Two(String theS)

17.    {18.       super("red");19.       twoS = theS;20.    }

21.    public String getS()22.    {23.        return twoS;24.    }25. }

26. public class Three extends Two

27. {28.    private String threeS;

29.    public Three(String theS)

30.    {31.       super("blue");32.       threeS = theS;33.    }

34.    public String getS()35.    {36.        return threeS;37.    }38. }

Exercise 0b - Polymorphism

What is the hierarchy?

Page 142

Page 143: Chapter Complete

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.

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()   {      System.out.print("title: " + title +                " (" + playingTime + " mins)");      if(gotIt) {         System.out.println("*");      } else {         System.out.println();      }      System.out.println(" " + comment);   }

public class Video extends Item{   private String director;

::

public class CD extends Item{   private String artist;   private int numberOfTracks;

::

public class Database{   private ArrayList items;

   public void list()   {

Page 143

Page 144: Chapter Complete

      for(Iterator iter = items.iterator(); iter.hasNext(); )      {         Item item = (Item)iter.next();         item.print();      }   }}

Exercise 1 - DoME print problem

In BlueJ

Open chapter08/dome-v2 Create a Video, CD and Database object.

o Use Database method addItem() to add the CD and Video object to the database.

Call the Database method list() to print the database.o Did the Item method print() execute?

Add print() methods for CD and Video classes.o Copy and paste print() from below.

Create a Video, CD and Database object.o Use Database method addItem() to add the CD

and Video object to the database. Call the Database method list() to print the database.

o Did the Item method print() execute?

Item Video CDpublic class Item{ private String title; private int playingTime; private boolean gotIt; private String comment;

 public void print() {   System.out.print("title: " + title +           " (" + playingTime + " mins)");   if(gotIt) {       System.out.println("*");   } else {      System.out.println();   }   System.out.println(" " + comment); }

public class Video extends Item{   private String director;

   public void print()   {      System.out.println("Video " +                 director);   }

::

public class CD extends Item{   private String artist;   private int numberOfTracks;

   public void print()   {      System.out.println("CD " + artist);      System.out.println(" tracks: " +                           numberOfTracks);   }

::

9.2 Static type and dynamic type

Problem

Page 144

Page 145: Chapter Complete

CD and Video cannot access Item fields so cannot print those fields. Adding CD or Video method print() overrides Item method print(). Database class should not call CD or Video method print() directly since that would

require modifying each time a new class was inherited from Item.

Solution

Define print() methods for CD, Video and Item classes. 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.dynamic type - The type a variable stores at the current time. Used to determine method to call at runtiime.

Exercise 1 demonstrated that CD and Video print() methods are called from list() method.

Reason is item variable dynamic type changes to CD when referencing a CD or Video when referencing a Video.

Dynamic type determines which print() is called. Static type used at compile time.

9.3 Overriding

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.

In the following, the print() methods of CD and Video override the print() method of Item for CD and Item objects.

Item Video CD

Page 145

Page 146: Chapter Complete

public class Item{ private String title; private int playingTime; private boolean gotIt; private String comment;

 public void print() {   System.out.print("title: " + title +            " (" + playingTime + " mins)");   if(gotIt) {      System.out.println("*");   } else {     System.out.println();   }   System.out.println(" " + comment); }

public class Video extends Item{  private String director;

 public void print() {    System.out.println("Video " +               director); }

::

public class CD extends Item{  private String artist;  private int numberOfTracks;

  public void print()  {    System.out.println("CD " + artist);    System.out.println(" tracks: " +                         numberOfTracks);  }

::

9.4 Dynamic method lookup

method lookup - How methods are called.

v1.print();

1. v1 accessed. 2. v1 found to be a Video object. 3. Video class has a print() method. 4. Video print() executed.

 

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.

Page 146

Page 147: Chapter Complete

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.

No changes to super class method.

Item Video CD

public class Item{ private String title; private int playingTime; private boolean gotIt; private String comment;

 public void print() {   System.out.print("title: " + title +             " (" + playingTime + " mins)");   if(gotIt) {      System.out.println("*");   } else {     System.out.println();   }   System.out.println(" " + comment);}

public class Video extends Item{  private String director;

  public void print() {     super.print();    System.out.println("Video " +                director); }

::

public class CD extends Item{ private String artist; private int numberOfTracks;

 public void print() {    super.print();   System.out.println("CD " + artist);   System.out.println(" tracks: " +                        numberOfTracks); }

::

Exercise 2 - Super call in methods

In BlueJ

Open chapter08/dome-v2 Add super.print() methods to CD and Video method print(). Create a Video, CD and Database object.

o Use Database method addItem() to add the CD and Video object to the database. Call the Database method list() to print the database.

o Did the Item, CD and Video method print() execute?

Page 147