Big Java book Cover

Chapter 3 – Implementing Classes

Chapter Goals

electronics

Instance Variables and Encapsulation

Instance Variables

Instance Variables

Instance Variables

Figure 2 - Instance Variables
Figure 2 Instance Variables

Syntax 3.1 Instance Variable Declaration

Syntax 3.1 Instance Variable Declaration

Instance Variables

clocks

 

These clocks have common behavior, but each of them has a different state. Similarly, objects of a class can have their instance variables set to different values.

The Methods of the Counter Class

The Methods of the Counter Class

Encapsulation

Encapsulation

thermostat

 

A thermostat functions as a "black box" whose inner workings are hidden.

section_1/Counter.java

Your browser does not support this feature

Self Check 3.1

Supply the body of a method public void unclick() that undoes an unwanted button click.

Self Check 3.2

Suppose you use a class Clock with private instance variables hours and minutes. How can you access these variables in your program?

Self Check 3.3

Consider the Counter class. A counter’s value starts at 0 and is advanced by the click method, so it should never be negative. Suppose you found a negative value variable during testing. Where would you look for the error?

Self Check 3.4

In Chapters 1 and 2, you used System.out as a black box to cause output to appear on the screen. Who designed and implemented System.out?

Self Check 3.5

Suppose you are working in a company that produces personal finance software. You are asked to design and implement a class for representing bank accounts. Who will be the users of your class?

Specifying the Public Interface of a Class

Specifying the Public Interface of a Class

Specifying the Public Interface of a Class: Method Declaration

Specifying the Public Interface of a Class

Specifying Constructors

Specifying Constructors: BankAccount

Specifying Constructors: BankAccount

BankAccount Public Interface

The constructors and methods of a class go inside the class declaration:
public class BankAccount
{
   // private instance variables--filled in later

   // Constructors
   public BankAccount()
   {
      // body--filled in later
   }
   public BankAccount(double initialBalance)
   {
      // body--filled in later
   }

   // Methods
   public void deposit(double amount)
   {
      // body--filled in later
   }
   public void withdraw(double amount)
   {
      // body--filled in later
   }
   public double getBalance()
   {
      // body--filled in later
   }
}

Specifying the Public Interface of a Class

Syntax 3.2 Class Declaration

Syntax 3.2 Class Declaration

Using the Public Interface

Commenting the Public Interface

Commenting the Public Interface - Documenting a method

Commenting the Public Interface - Documenting a method

Commenting the Public Interface - Documenting a class

Method Summary

screen shot of method summary
Figure 3 A Method Summary Generated by javadoc

Method Details

method details
Figure 4 Method Detail Generated by javadoc

Self Check 3.6

How can you use the methods of the public interface to empty the harrysChecking bank account?

Self Check 3.7

What is wrong with this sequence of statements?
BankAccount harrysChecking = new BankAccount(10000); 
System.out.println(harrysChecking.withdraw(500));

Self Check 3.8

Suppose you want a more powerful bank account abstraction that keeps track of an account number in addition to the balance. How would you change the public interface to accommodate this enhancement?

Self Check 3.9

Suppose we enhance the BankAccount class so that each account has an account number. Supply a documentation comment for the constructor

public BankAccount(int accountNumber, double initialBalance)

Self Check 3.10

Why is the following documentation comment questionable?

/**
   Each account has an account number.
   @return the account number of this account
*/
public int getAccountNumber()

Providing the Class Implementation

Providing Instance Variables

Providing Instance Variables

backpacker analogy with instance variables

 

Like a wilderness explorer who needs to carry all items that may be needed, an object needs to store the data required for its method calls.

Providing Constructors

Providing Constructors - Tracing the Statement

Steps carried out when the following statement is executed:

BankAccount harrysChecking = new BankAccount(1000);  

Providing Constructors - Tracing the Statement

diagram of constructor
Figure 5 How a Constructor Works

Providing Constructors

Assembling a house

 

A constructor is like a set of assembly instructions for an object.

Providing Methods

Providing Methods - continued

Table 1 Implementing Classes

implementing classes

section_3/BankAccount.java

Your browser does not support this feature

Self Check 3.11

Suppose we modify the BankAccount class so that each bank account has an account number. How does this change affect the instance variables?

Self Check 3.12

Why does the following code not succeed in robbing mom's bank account?
public class BankRobber 
{ 
   public static void main(String[] args) 
   { 
      BankAccount momsSavings = new BankAccount(1000); 
      momsSavings.balance = 0;  
   } 
}

Self Check 3.13

The Rectangle class has four instance variables: x, y, width, and height. Give a possible implementation of the getWidth method.

Self Check 3.14

Give a possible implementation of the translate method of the Rectangle class.

Unit Testing

Unit Testing

Unit Testing

engineer testing a part

 

An engineer tests a part in isolation.
This is an example of unit testing.

Unit Testing with Bluej

unit testing with Bluej
Figure 6 The Return Value of the getBalance Method in BlueJ

section_4/BankAccountTester.java

Your browser does not support the <object> tag.

Program Run:

Unit Testing - Building a program

Self Check 3.15

When you run the BankAccountTester program, how many objects of class BankAccount are constructed? How many objects of type BankAccountTester?

Self Check 3.16

Why is the BankAccountTester class unnecessary in development environments that allow interactive testing, such as BlueJ?

Problem Solving: Tracing Objects

Problem Solving: Tracing Objects

Problem Solving: Tracing Objects

Problem Solving: Tracing Objects

Self Check 3.17

Consider a Car class that simulates fuel consumption in a car. We will assume a fixed efficiency (in miles per gallon) that is supplied in the constructor. There are methods for adding gas, driving a given distance, and checking the amount of gas left in the tank. Make a card for a Car object, choosing suitable instance variables and showing their values after the object was constructed.

Self Check 3.18

Trace the following method calls:

Car myCar(25);
myCar.addGas(20);
myCar.drive(100);
myCar.drive(200);
myCar.addGas(5); 

Self Check 3.19

odometer

Suppose you are asked to simulate the odometer of the car, by adding a method getMilesDriven.
Add an instance variable to the object’s card that is suitable for computing this method’s result.


Self Check 3.20

Trace the methods of Self Check 18, updating the instance variable that you added in Self Check 19.

Local Variables

Local Variables

Self Check 3.21

What do local variables and parameter variables have in common? In which essential aspect do they differ?

Self Check 3.22

Why was it necessary to introduce the local variable change in the giveChange method? That is, why didn’t the method simply end with the statement
return payment - purchase;

Self Check 3.23

Consider a CashRegister object reg1 whose payment instance variable has the value 20 and whose purchase instance variable has the value 19.5. Trace the call reg1.giveChange(). Include the local variable change. Draw an X in its column when the variable ceases to exist.

The this Reference

The this Reference

The this Reference

The this Reference

The this Reference

Figure 8 - The Implicit Parameter of a Method Call
Figure 7 The Implicit Parameter of a Method Call

The this Reference

The this Reference

Self Check 3.24

How many implicit and explicit parameters does the withdraw method of the BankAccount class have, and what are their names and types?

Self Check 3.25

In the deposit method, what is the meaning of this.amount? Or, if the expression has no meaning, why not?

Self Check 3.26

How many implicit and explicit parameters does the main method of the BankAccountTester class have, and what are they called?

Shape Classes

Drawing Cars

Goal: draw two cars - one in top-left corner of window, and another in the bottom right.
Figure 9 - The Car Component Draws Two Car Shapes
Figure 8 The Car Component Draws Two Car Shapes

Plan Complex Shapes on Graph Paper

Figure 10 - Using Graph Paper to Find Shape Coordinates

Figure 9 Using Graph Paper to Find Shape Coordinates

Drawing Cars

The program that produces the drawing is composed of three classes:

Drawing Cars

section_8/Car.java

Your browser does not support this feature

section_8/CarComponent.java

Your browser does not support this feature

section_8/CarViewer.java

Your browser does not support this feature

Self Check 3.27

Which class needs to be modified to have the two cars positioned next to each other?

Self Check 3.28

Which class needs to be modified to have the car tires painted in black, and what modification do you need to make?

Self Check 3.29

How do you make the cars twice as big?