SlideShare a Scribd company logo
1 of 108
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 3 – Implementing Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To become familiar with the process of implementing classes
 To be able to implement and test simple methods
 To understand the purpose and use of constructors
 To understand how to access instance variables and local variables
 To be able to write javadoc comments
 To implement classes for drawing graphical shapes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
A Simple Counter Class
Figure 1 Tally counter
 Simulator statements:
Counter tally = new Counter();
tally.click();
tally.click();
int result = tally.getValue(); // Sets result to 2
 Each counter needs to store a variable that keeps track of
the number of simulated button clicks.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Counter.java: Implementation of Counter class
1 /**
2 This class models a tally counter.
3 */
4 public class Counter
5 {
6 private long value;
7
8 /**
9 Gets the current value of this counter.
10 @return the current value
11 */
12 public long getValue()
13 {
14 return value;
15 }
16
17 /**
18 Advances the value of this counter by 1.
19 */
20 public void click()
21 {
22 value = value + 1;
23 }
24
25 /**
26 Resets the value of this counter to 0.
27 */
28 public void reset()
29 {
30 value = 0;
31 }
32 }
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Instance Variables
 Instance variables store the data of an object.
 Instance of a class: an object of the class.
 An instance variable is a storage location present in each
object of the class.
 The class declaration specifies the instance variables:
public class Counter
{
private int value;
…
}
 An object's instance variables store the data required for
executing its methods.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
Instance Variables
 An instance variable declaration consists of the following
parts:
• access specifier (private)
• type of variable (such as int)
• name of variable (such as value)
 You should declare all instance variables as private.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Instance Variables are Different for Each Instance
(object) of a class
 Each object of a class has its own set of instance variables.
Figure 2 Instance Variables
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Instance Variables
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Syntax 3.1 Instance Variable Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
The Methods of the Counter Class
 The click method advances the counter value by 1:
public void click()
{
value = value + 1;
}
• Affects the value of the instance variable of the object on which the
method is invoked
• The method call concertCounter.click();
o Advances the value variable of the concertCounter object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
The Methods of the Counter Class
 The getValue method returns the current value:
public int getValue()
{
return value;
}
 The return statement
• Terminates the method call
• Returns a result (the return value) to the method's caller
 Private instance variables can only be accessed by
methods of the same class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Counter.java: Implementation of Counter class
1 /**
2 This class models a tally counter.
3 */
4 public class Counter
5 {
6 private double value;
7
8 /**
9 Gets the current value of this counter.
10 @return the current value
11 */
12 public long getValue()
13 {
14 return Math.round(value);
15 }
16
17 /**
18 Advances the value of this counter by 1.
19 */
20 public void click()
21 {
22 value = value + 1;
23 }
24
25 /**
26 Resets the value of this counter to 0.
27 */
28 public void reset()
29 {
30 value = 0;
31 }
32 }
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Encapsulation
 Encapsulation is the process of hiding implementation
details and providing methods for data access.
 To encapsulate data:
• Declare instance variables as private and
• Declare public methods that access the variables
 Encapsulation allows a programmer to use a class without
having to know its implementation.
 Information hiding makes it simpler for the implementor of a
class to locate errors and change implementations.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Encapsulation
 When you assemble classes, like Rectangle and String, into
programs you are like a contractor installing a thermostat.
 When you implement your own classes you are like the
manufacturer who puts together a thermostat out of parts.
A thermostat functions as a “black
box” whose inner workings are
hidden.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
section_1/Counter.java
17 /**
18 Advances the value of this counter by 1.
19 */
20 public void click()
21 {
22 value = value + 1;
23 }
24
25 /**
26 Resets the value of this counter to 0.
27 */
28 public void reset()
29 {
30 value = 0;
31 }
32 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
Self Check 3.1
Supply the body of a method public void unclick() that
undoes an unwanted button click.
Answer:
public void unclick()
{
value = value – 1;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
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?
Answer: You can only access them by invoking the
methods of the Clock class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
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?
Answer: In one of the methods of the Counter class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
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?
Answer: The programmers who designed and
implemented the Java library.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Specifying the Public Interface of a Class
 In order to implement a class, you first need to know which
methods are required.
 Essential behavior of a bank account:
• deposit money
• withdraw money
• get balance
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Specifying the Public Interface of a Class
 We want to support method calls such as the following:
harrysChecking.deposit(2000);
harrysChecking.withdraw(500);
System.out.println(harrysChecking.getBalance());
 Here are the method headers needed for a BankAccount class:
public void deposit(double amount)
public void withdraw(double amount)
public double getBalance()
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Specifying the Public Interface of a Class:
Method Declaration
 A method's body consisting of statements that are executed when the method is
called:
public void deposit(double amount)
{
implementation - filled in later
}
 You can fill in the method body so it compiles:
public double getBalance()
{
// TODO: fill in implementation
return 0;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Specifying the Public Interface of a Class
 BankAccount methods were declared as public.
 public methods can be called by all other methods in the
program.
 Methods can also be declared private
• private methods only be called by other methods in the same class
• private methods are not part of the public interface
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Specifying Constructors: BankAccount
 Two constructors
public BankAccount()
public BankAccount(double initialBalance)
 Usage
BankAccount harrysChecking = new BankAccount();
BankAccount momsSavings = new BankAccount(5000);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
Specifying Constructors
 Initialize objects
 Set the initial data for objects
 Similar to a method with two differences:
• The name of the constructor is always the same as the name of the class
• Constructors have no return type
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Specifying Constructors: BankAccount
 The constructor name is always the same as the class name.
 The compiler can tell them apart because they take different
arguments.
 A constructor that takes no arguments is called a no-argument
constructor.
 BankAccount's no-argument constructor - header and body:
public BankAccount()
{
constructor body—implementation filled in later
}
 The statements in the constructor body will set the instance
variables of the object.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
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
} Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
BankAccount Public Interface
// 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
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Specifying the Public Interface of a Class
 public constructors and methods of a class form the public
interface of the class.
 These are the operations that any programmer can use.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Syntax 3.2 Class Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
Using the Public Interface
 Example: transfer money
// Transfer from one account to another
double transferAmount = 500;
momsSavings.withdraw(transferAmount);
harrysChecking.deposit(transferAmount);
 Example: add interest
double interestRate = 5; // 5 percent interest
double interestAmount =
momsSavings.getBalance() * interestRate / 100;
momsSavings.deposit(interestAmount);
 Programmers use objects of the BankAccount class to carry out
meaningful tasks
• without knowing HOW the BankAccount objects store their data
• without knowing HOW the BankAccount methods do their work
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
Commenting the Public Interface –
Documenting a Method
 Start the comment with a /**.
 Describe the method’s purpose.
 Describe each parameter:
• start with @param
• name of the parameter that holds the argument
• a short explanation of the argument
 Describe the return value:
• start with @return
• describe the return value
 Omit @param tag for methods that have no arguments.
 Omit the @return tag for methods whose return type is void.
 End with */.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Commenting the Public Interface –
Documenting a Method
 Example:
/** Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
implementation—filled in later
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Commenting the Public Interface –
Documenting a Method
 Example:
/** Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
implementation—filled in later
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Commenting the Public Interface –
Documenting a Class
 Place above the class declaration.
 Supply a brief comment explaining the class's purpose.
 Example:
/** A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{ . . . }
 Provide documentation comments for:
• every class
• every method
• every parameter variable
• every return value
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
Method Summary
Figure 3 A Method Summary Generated by javadoc
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
Method Details
Figure 4 Method Detail Generated by javadoc
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
Self Check 3.6
How can you use the methods of the public interface to
empty the harrysChecking bank account?
Answer:
harrysChecking.withdraw(harrysChecking.getBalance())
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
Self Check 3.7
What is wrong with this sequence of statements?
BankAccount harrysChecking = new BankAccount(10000);
System.out.println(harrysChecking.withdraw(500));
Answer: The withdraw method has return type void. It
doesn’t return a value. Use the getBalance method to
obtain the balance after the withdrawal.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
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?
Answer: Add an accountNumber parameter to the
constructors, and add a getAccountNumber method.
There is no need for a setAccountNumber method – the
account number never changes after construction.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
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)
Answer:
/**
Constructs a new bank account with a given initial balance.
@param accountNumber the account number for this account
@param initialBalance the initial balance for this account
*/
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
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()
Answer: The first sentence of the method description
should describe the method—it is displayed in isolation
in the summary table.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Providing the Class Implementation
 The implementation of a class consists of:
• instance variables
• the bodies of constructors
• the bodies of methods.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Providing Instance Variables
 Determine the data that each bank account object contains.
 What does the object need to remember so that it can carry out
its methods?
 Each bank account object only needs to store the current
balance.
 BankAccount instance variable declaration:
public class BankAccount
{
private double balance;
// Methods and constructors below
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Providing 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Providing Constructors
 Constructor's job is to initialize the instance variables of the
object.
 The no-argument constructor sets the balance to zero.
public BankAccount()
{
balance = 0;
}
 The second constructor sets the balance to the value supplied
as the construction argument.
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Providing Constructors - Tracing the
Statement
Steps carried out when the following statement is executed:
BankAccount harrysChecking = new BankAccount(1000);
 Create a new object of type BankAccount.
 Call the second constructor
• because an argument is supplied in the constructor call
 Set the parameter variable initialBalance to 1000.
 Set the balance instance variable of the newly created object to
initialBalance.
 Return an object reference, that is, the memory location of the
object.
 Store that object reference in the harrysChecking variable.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
Providing Constructors - Tracing the
Statement
Figure 5 How a Constructor
Works
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
Providing Constructors
A constructor is like a set of assembly
instructions for an object.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
Providing Methods
 Is the method an accessor or a mutator
• Mutator method
• Update the instance variables in some way
• Accessor method
• Retrieves or computes a result
 deposit method - a mutator method
• Updates the balance
public void deposit(double amount)
{
balance = balance + amount;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
Providing Methods
 withdraw method - another mutator
public void withdraw(double amount)
{
balance = balance – amount;
}
 getBalance method - an accessor method
• Returns a value
public double getBalance()
{
return balance;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Table 1 Implementing Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
section_3/BankAccount.java
1 /**
2 A bank account has a balance that can be changed by
3 deposits and withdrawals.
4 */
5 public class BankAccount
6 {
7 private double balance;
8
9 /**
10 Constructs a bank account with a zero balance.
11 */
12 public BankAccount()
13 {
14 balance = 0;
15 }
16
17 /**
18 Constructs a bank account with a given balance.
19 @param initialBalance the initial balance
20 */
21 public BankAccount(double initialBalance)
22 {
23 balance = initialBalance;
24 }
25 Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
section_3/BankAccount.java
26 /**
27 Deposits money into the bank account.
28 @param amount the amount to deposit
29 */
30 public void deposit(double amount)
31 {
32 balance = balance + amount;
33 }
34
35 /**
36 Withdraws money from the bank account.
37 @param amount the amount to withdraw
38 */
39 public void withdraw(double amount)
40 {
41 balance = balance - amount;
42 }
43
44 /**
45 Gets the current balance of the bank account.
46 @return the current balance
47 */
48 public double getBalance()
49 {
50 return balance;
51 }
52 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
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?
Answer: An instance variable needs to be added to the
class:
private int accountNumber;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
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;
}
}
Answer: Because the balance instance variable is
accessed from the main method of BankRobber. The
compiler will report an error because main has no
access to BankAccount instance variables.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
Self Check 3.13
The Rectangle class has four instance variables: x, y, width,
and height. Give a possible implementation of the getWidth
method.
Answer:
public int getWidth()
{
return width;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Self Check 3.14
Give a possible implementation of the translate method of
the Rectangle class.
Answer: There is more than one correct answer. One
possible implementation is as follows:
public void translate(int dx, int dy)
{
int newx = x + dx;
x = newx;
int newy = y + dy;
y = newy;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Unit Testing
 BankAccount.java can not be executed:
• It has no main method
• Most classes do not have a main method
 Before using BankAccount.java in a larger program:
• You should test in isolation
 Unit test: verifies that a class works correctly in isolation,
outside a complete program.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Unit Testing
 To test a class, either
• use an environment for interactive testing, or
• write a tester class to execute test instructions.
 Tester class: a class with a main method that contains
statements to test another class.
 Typically carries out the following steps:
1. Construct one or more objects of the class that is being tested
2. Invoke one or more methods
3. Print out one or more results
4. Print the expected results
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
Unit Testing
An engineer tests a part in isolation. This
is an example of unit testing.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Unit Testing with BlueJ
Figure 6 The Return Value of the getBalance Method in BlueJ
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
section_4/BankAccountTester.java
1 /**
2 A class to test the BankAccount class.
3 */
4 public class BankAccountTester
5 {
6 /**
7 Tests the methods of the BankAccount class.
8 @param args not used
9 */
10 public static void main(String[] args)
11 {
12 BankAccount harrysChecking = new BankAccount();
13 harrysChecking.deposit(2000);
14 harrysChecking.withdraw(500);
15 System.out.println(harrysChecking.getBalance());
16 System.out.println("Expected: 1500");
17 }
18 }
Program Run:
1500
Expected: 1500
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
Unit Testing – Building a Program
 To produce a program: combine both BankAccount and
BankAccountTester classes.
 Details for building the program vary.
 In most environments, you need to carry out these steps:
1. Make a new subfolder for your program
2. Make two files, one for each class
3. Compile both files
4. Run the test program
 BankAccount and BankAccountTest have entirely different
purposes:
• BankAccount class describes objects that compute bank balances
• BankAccountTester class runs tests that put a BankAccount object
through its paces
Copyright © 2014 by John Wiley & Sons. All rights reserved. 65
Self Check 3.15
When you run the BankAccountTester program, how many
objects of class BankAccount are constructed? How many
objects of type BankAccountTester?
Answer: One BankAccount object, no BankAccountTester
object. The purpose of the BankAccountTester class is
merely to hold the main method.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
Self Check 3.16
Why is the BankAccountTester class unnecessary in
development environments that allow interactive testing,
such as BlueJ?
Answer: In those environments, you can issue interactive
commands to construct BankAccount objects, invoke
methods, and display their return values.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
Problem Solving: Tracing Objects
 Important skill: the ability to simulate the actions of a program
with pencil and paper.
 Use an index card or a sticky note for each object:
• Write the methods on the front
• Make a table for the values of the instance variables on the back
 CashRegister class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
Problem Solving: Tracing Objects
 When an object is constructed, fill in the initial values of the
instance variables.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Problem Solving: Tracing Objects
 Update the values of the instance variables when a mutator
method is called.
 After a call to cashRegister's recordPurchase method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 70
Problem Solving: Tracing Objects
 More than one object: create multiple cards
Copyright © 2014 by John Wiley & Sons. All rights reserved. 71
Problem Solving: Tracing Objects
 Useful when enhancing a class.
 Enhance CashRegister class to compute the sales tax.
 Add methods recordTaxablePurchase and getSalesTax to the
front of the card.
 Don’t have enough information to compute sales tax:
• need tax rate
• need total of the taxable items
 Need additional instance variables for:
• taxRate
• taxablePurchase
Copyright © 2014 by John Wiley & Sons. All rights reserved. 72
Problem Solving: Tracing Objects
 Example: CashRegister class enhancement
• The code:
CashRegister reg3(7.5); // 7.5 percent sales tax
reg3.recordPurchase(3.95); // Not taxable
reg3.recordTaxablePurchase(19.95); // Taxable
• The card:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 73
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.
Answer:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 74
Self Check 3.18
Trace the following method calls:
Car myCar(25);
myCar.addGas(20);
myCar.drive(100);
myCar.drive(200);
myCar.addGas(5);
Answer:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 75
Self Check 3.19
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.
Answer:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 76
Self Check 3.20
Trace the methods of Self Check 18, updating the instance
variable that you added in Self Check 19.
Answer:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 77
Local Variables
 Local variables are declared in the body of a method:
public double giveChange()
{
double change = payment – purchase;
purchase = 0;
payment = 0;
return change;
}
 When a method exits, its local variables are removed.
 Parameter variables are declared in the header of a method:
public void enterPayment(double amount)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 78
Local Variables
 Local and parameter variables belong to methods:
• When a method runs, its local and parameter variables come to life
• When the method exits, they are removed immediately
 Instance variables belong to objects, not methods:
• When an object is constructed, its instance variables are created
• The instance variables stay alive until no method uses the object any
longer
 Instance variables are initialized to a default value:
• Numbers are initialized to 0
• Object references are set to a special value called null
• A null object reference refers to no object at all
 You must initialize local variables:
• The compiler complains if you do not
Copyright © 2014 by John Wiley & Sons. All rights reserved. 79
Self Check 3.21
What do local variables and parameter variables have in
common? In which essential aspect do they differ?
Answer: Variables of both categories belong to methods –
they come alive when the method is called, and they die
when the method exits. They differ in their initialization.
Parameter variables are initialized with the call values;
local variables must be explicitly initialized.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 80
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;
Answer: After computing the change due, payment and
purchase were set to zero. If the method returned
payment - purchase, it would always return zero.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 81
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.
Answer:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 82
The this Reference
 Two types of inputs are passed when a method is called:
• The object on which you invoke the method
• The method arguments
 In the call momsSavings.deposit(500) the method needs to
know:
• The account object (momsSavings)
• The amount being deposited (500)
 The implicit parameter of a method is the object on which the
method is invoked.
 All other parameter variables are called explicit parameters.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
The this Reference
 Look at this method:
public void deposit(double amount)
{
balance = balance + amount;
}
• amount is the explicit parameter
• The implicit parameter(momSavings) is not seen
• balance means momSavings.balance
 When you refer to an instance variable inside a method, it
means the instance variable of the implicit parameter.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
The this Reference
 The this reference denotes the implicit parameter
balance = balance + amount;
actually means
this.balance = this.balance + amount;
 When you refer to an instance variable in a method, the
compiler automatically applies it to the this reference.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
The this Reference
 Some programmers feel that inserting the this reference before
every instance variable reference makes the code clearer:
public BankAccount(double initialBalance)
{
this.balance = initialBalance;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
The this Reference
Figure 7 The Implicit Parameter of a Method Call
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
The this Reference
 The this reference can be used to distinguish between instance
variables and local or parameter variables:
public BankAccount(double balance)
{
this.balance = balance;
}
 A local variable shadows an instance variable with the same
name.
• You can access the instance variable name through the this reference.
Code Defensively: Avoid hard to find bugs!!
Copyright © 2014 by John Wiley & Sons. All rights reserved. 88
The this Reference
 In Java, local and parameter variables are considered first
when looking up variable names.
 Statement
this.balance = balance;
means: “Set the instance variable balance to the parameter
variable balance”.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 89
The this Reference
 A method call without an implicit parameter is applied to the
same object.
 Example:
public class BankAccount
{
. . .
public void monthlyFee()
{
withdraw(10); // Withdraw $10 from this account
}
}
 The implicit parameter of the withdraw method is the (invisible)
implicit parameter of the monthlyFee method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 90
The this Reference
 You can use the this reference to make the method easier to
read:
public class BankAccount
{
. . .
public void monthlyFee()
{
this.withdraw(10); // Withdraw $10 from this account
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 91
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?
Answer: One implicit parameter, called this, of type
BankAccount, and one explicit parameter, called amount,
of type double.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 92
Self Check 3.25
In the deposit method, what is the meaning of this.amount? Or, if the
expression has no meaning, why not?
Answer: It is not a legal expression. this is of type
BankAccount and the BankAccount class has no
instance variable named amount.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 93
Self Check 3.26
How many implicit and explicit parameters does the main method of the
BankAccountTester class have, and what are they called?
Answer: No implicit parameter — the main method is not
invoked on any object — and one explicit parameter,
called args.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 94
Shape Classes
 Good practice: Make a class for each part of a drawing that
occurs more than once.
public class Car
{
public Car(int x, int y)
{
// Remember position
. . .
}
public void draw(Graphics2D g2)
{
// Drawing instructions
. . .
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 95
Drawing Cars
Goal: draw two cars - one in top-left corner of window, and
another in the bottom right.
Figure 8 The Car Component Draws Two Car Shapes
Copyright © 2014 by John Wiley & Sons. All rights reserved. 96
Plan Complex Shapes on Graph Paper
Figure 9 Using Graph Paper to Find Shape Coordinates
Copyright © 2014 by John Wiley & Sons. All rights reserved. 97
Drawing Cars
The program that produces the drawing is composed of three
classes:
 The Car class is responsible for drawing a single car.
• Two objects of this class are constructed, one for each car.
 The CarComponent class displays the drawing
 The CarViewer class shows a frame that contains a
CarComponent
Copyright © 2014 by John Wiley & Sons. All rights reserved. 98
Drawing Cars
 The paintComponent method of the CarComponent class
draws the two cars.
 To compute bottom right position:
Car car1 = new Car(0, 0);
int x = getWidth() – 60;
int y = getHeight() – 30;
Car car2 = new Car(x, y);
• getWidth and getHeight return the dimensions of the CarComponent
• Subtract the dimensions of the car to determine the position of car2
 When window is resized paintComponent is called
 Car position is recomputed using current dimensions
Copyright © 2014 by John Wiley & Sons. All rights reserved. 99
section_8/Car.java
1 import java.awt.Graphics2D;
2 import java.awt.Rectangle;
3 import java.awt.geom.Ellipse2D;
4 import java.awt.geom.Line2D;
5 import java.awt.geom.Point2D;
6
7 /**
8 A car shape that can be positioned anywhere on the screen.
9 */
10 public class Car
11 {
12 private int xLeft;
13 private int yTop;
14
15 /**
16 Constructs a car with a given top left corner.
17 @param x the x coordinate of the top left corner
18 @param y the y coordinate of the top left corner
19 */
20 public Car(int x, int y)
21 {
22 xLeft = x;
23 yTop = y;
24 }
25 Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 100
section_8/Car.java
26 /**
27 Draws the car.
28 @param g2 the graphics context
29 */
30 public void draw(Graphics2D g2)
31 {
32 Rectangle body = new Rectangle(xLeft, yTop + 10, 60, 10);
33 Ellipse2D.Double frontTire
34 = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10);
35 Ellipse2D.Double rearTire
36 = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10);
37
38 // The bottom of the front windshield
39 Point2D.Double r1 = new Point2D.Double(xLeft + 10, yTop + 10);
40 // The front of the roof
41 Point2D.Double r2 = new Point2D.Double(xLeft + 20, yTop);
42 // The rear of the roof
43 Point2D.Double r3 = new Point2D.Double(xLeft + 40, yTop);
44 // The bottom of the rear windshield
45 Point2D.Double r4 = new Point2D.Double(xLeft + 50, yTop + 10);
46
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 101
section_8/Car.java
47 Line2D.Double frontWindshield = new Line2D.Double(r1, r2);
48 Line2D.Double roofTop = new Line2D.Double(r2, r3);
49 Line2D.Double rearWindshield = new Line2D.Double(r3, r4);
50
51 g2.draw(body);
52 g2.draw(frontTire);
53 g2.draw(rearTire);
54 g2.draw(frontWindshield);
55 g2.draw(roofTop);
56 g2.draw(rearWindshield);
57 }
58 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 102
section_8/CarComponent.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import javax.swing.JComponent;
4
5 /**
6 This component draws two car shapes.
7 */
8 public class CarComponent extends JComponent
9 {
10 public void paintComponent(Graphics g)
11 {
12 Graphics2D g2 = (Graphics2D) g;
13
14 Car car1 = new Car(0, 0);
15
16 int x = getWidth() - 60;
17 int y = getHeight() - 30;
18
19 Car car2 = new Car(x, y);
20
21 car1.draw(g2);
22 car2.draw(g2);
23 }
24 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 103
section_8/CarViewer.java
1 import javax.swing.JFrame;
2
3 public class CarViewer
4 {
5 public static void main(String[] args)
6 {
7 JFrame frame = new JFrame();
8
9 frame.setSize(300, 400);
10 frame.setTitle("Two cars");
11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12
13 CarComponent component = new CarComponent();
14 frame.add(component);
15
16 frame.setVisible(true);
17 }
18 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 104
UML Class Diagrams: Arrow Types
Copyright © 2014 by John Wiley & Sons. All rights reserved. 105
UML Class Diagrams
JComponent
CarComponent JFrame
Car
Can you figure out which arrows reflect the
relationships among these classes?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 106
Self Check 3.27
Which class needs to be modified to have the two cars
positioned next to each other?
Answer: CarComponent
Copyright © 2014 by John Wiley & Sons. All rights reserved. 107
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?
Answer: In the draw method of the Car class, call
g2.fill(frontTire);
g2.fill(rearTire);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 108
Self Check 3.29
How do you make the cars twice as big?
Answer: Double all measurements in the draw method of
the Car class.

More Related Content

What's hot

What's hot (20)

Icom4015 lecture3-s18
Icom4015 lecture3-s18Icom4015 lecture3-s18
Icom4015 lecture3-s18
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Icom4015 lecture4-f17
Icom4015 lecture4-f17Icom4015 lecture4-f17
Icom4015 lecture4-f17
 
Icom4015 lecture13-f16
Icom4015 lecture13-f16Icom4015 lecture13-f16
Icom4015 lecture13-f16
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 

Similar to CiIC4010-chapter-2-f17

Chapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionChapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionIt Academy
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookRoman Tsypuk
 
Programming II hiding, and .pdf
 Programming II hiding, and .pdf Programming II hiding, and .pdf
Programming II hiding, and .pdfaludin007
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsKuntal Bhowmick
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsKuntal Bhowmick
 
Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6helpido9
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application javagthe
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 
Assignment 4- Implementing a Banking Application Due See course shel.pdf
 Assignment 4- Implementing a Banking Application Due See course shel.pdf Assignment 4- Implementing a Banking Application Due See course shel.pdf
Assignment 4- Implementing a Banking Application Due See course shel.pdfamarhandi
 

Similar to CiIC4010-chapter-2-f17 (20)

Chapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class ConstructionChapter 5:Understanding Variable Scope and Class Construction
Chapter 5:Understanding Variable Scope and Class Construction
 
Ch03
Ch03Ch03
Ch03
 
Ch03
Ch03Ch03
Ch03
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
 
C#2
C#2C#2
C#2
 
Programming II hiding, and .pdf
 Programming II hiding, and .pdf Programming II hiding, and .pdf
Programming II hiding, and .pdf
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
 
Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application java
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
basic concepts
basic conceptsbasic concepts
basic concepts
 
Class
ClassClass
Class
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 
Assignment 4- Implementing a Banking Application Due See course shel.pdf
 Assignment 4- Implementing a Banking Application Due See course shel.pdf Assignment 4- Implementing a Banking Application Due See course shel.pdf
Assignment 4- Implementing a Banking Application Due See course shel.pdf
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 

Recently uploaded

power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 

Recently uploaded (20)

power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 

CiIC4010-chapter-2-f17

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 3 – Implementing Classes
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To become familiar with the process of implementing classes  To be able to implement and test simple methods  To understand the purpose and use of constructors  To understand how to access instance variables and local variables  To be able to write javadoc comments  To implement classes for drawing graphical shapes
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 A Simple Counter Class Figure 1 Tally counter  Simulator statements: Counter tally = new Counter(); tally.click(); tally.click(); int result = tally.getValue(); // Sets result to 2  Each counter needs to store a variable that keeps track of the number of simulated button clicks.
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Counter.java: Implementation of Counter class 1 /** 2 This class models a tally counter. 3 */ 4 public class Counter 5 { 6 private long value; 7 8 /** 9 Gets the current value of this counter. 10 @return the current value 11 */ 12 public long getValue() 13 { 14 return value; 15 } 16 17 /** 18 Advances the value of this counter by 1. 19 */ 20 public void click() 21 { 22 value = value + 1; 23 } 24 25 /** 26 Resets the value of this counter to 0. 27 */ 28 public void reset() 29 { 30 value = 0; 31 } 32 } Continued
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Instance Variables  Instance variables store the data of an object.  Instance of a class: an object of the class.  An instance variable is a storage location present in each object of the class.  The class declaration specifies the instance variables: public class Counter { private int value; … }  An object's instance variables store the data required for executing its methods.
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 Instance Variables  An instance variable declaration consists of the following parts: • access specifier (private) • type of variable (such as int) • name of variable (such as value)  You should declare all instance variables as private.
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Instance Variables are Different for Each Instance (object) of a class  Each object of a class has its own set of instance variables. Figure 2 Instance Variables
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 Instance Variables 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.
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 Syntax 3.1 Instance Variable Declaration
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 The Methods of the Counter Class  The click method advances the counter value by 1: public void click() { value = value + 1; } • Affects the value of the instance variable of the object on which the method is invoked • The method call concertCounter.click(); o Advances the value variable of the concertCounter object
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 The Methods of the Counter Class  The getValue method returns the current value: public int getValue() { return value; }  The return statement • Terminates the method call • Returns a result (the return value) to the method's caller  Private instance variables can only be accessed by methods of the same class.
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Counter.java: Implementation of Counter class 1 /** 2 This class models a tally counter. 3 */ 4 public class Counter 5 { 6 private double value; 7 8 /** 9 Gets the current value of this counter. 10 @return the current value 11 */ 12 public long getValue() 13 { 14 return Math.round(value); 15 } 16 17 /** 18 Advances the value of this counter by 1. 19 */ 20 public void click() 21 { 22 value = value + 1; 23 } 24 25 /** 26 Resets the value of this counter to 0. 27 */ 28 public void reset() 29 { 30 value = 0; 31 } 32 } Continued
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Encapsulation  Encapsulation is the process of hiding implementation details and providing methods for data access.  To encapsulate data: • Declare instance variables as private and • Declare public methods that access the variables  Encapsulation allows a programmer to use a class without having to know its implementation.  Information hiding makes it simpler for the implementor of a class to locate errors and change implementations.
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Encapsulation  When you assemble classes, like Rectangle and String, into programs you are like a contractor installing a thermostat.  When you implement your own classes you are like the manufacturer who puts together a thermostat out of parts. A thermostat functions as a “black box” whose inner workings are hidden.
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 section_1/Counter.java 17 /** 18 Advances the value of this counter by 1. 19 */ 20 public void click() 21 { 22 value = value + 1; 23 } 24 25 /** 26 Resets the value of this counter to 0. 27 */ 28 public void reset() 29 { 30 value = 0; 31 } 32 }
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 Self Check 3.1 Supply the body of a method public void unclick() that undoes an unwanted button click. Answer: public void unclick() { value = value – 1; }
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 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? Answer: You can only access them by invoking the methods of the Clock class.
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 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? Answer: In one of the methods of the Counter class.
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 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? Answer: The programmers who designed and implemented the Java library.
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Specifying the Public Interface of a Class  In order to implement a class, you first need to know which methods are required.  Essential behavior of a bank account: • deposit money • withdraw money • get balance
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Specifying the Public Interface of a Class  We want to support method calls such as the following: harrysChecking.deposit(2000); harrysChecking.withdraw(500); System.out.println(harrysChecking.getBalance());  Here are the method headers needed for a BankAccount class: public void deposit(double amount) public void withdraw(double amount) public double getBalance()
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Specifying the Public Interface of a Class: Method Declaration  A method's body consisting of statements that are executed when the method is called: public void deposit(double amount) { implementation - filled in later }  You can fill in the method body so it compiles: public double getBalance() { // TODO: fill in implementation return 0; }
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Specifying the Public Interface of a Class  BankAccount methods were declared as public.  public methods can be called by all other methods in the program.  Methods can also be declared private • private methods only be called by other methods in the same class • private methods are not part of the public interface
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Specifying Constructors: BankAccount  Two constructors public BankAccount() public BankAccount(double initialBalance)  Usage BankAccount harrysChecking = new BankAccount(); BankAccount momsSavings = new BankAccount(5000);
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 Specifying Constructors  Initialize objects  Set the initial data for objects  Similar to a method with two differences: • The name of the constructor is always the same as the name of the class • Constructors have no return type
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Specifying Constructors: BankAccount  The constructor name is always the same as the class name.  The compiler can tell them apart because they take different arguments.  A constructor that takes no arguments is called a no-argument constructor.  BankAccount's no-argument constructor - header and body: public BankAccount() { constructor body—implementation filled in later }  The statements in the constructor body will set the instance variables of the object.
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 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 } Continued
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 BankAccount Public Interface // 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 } }
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Specifying the Public Interface of a Class  public constructors and methods of a class form the public interface of the class.  These are the operations that any programmer can use.
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Syntax 3.2 Class Declaration
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 Using the Public Interface  Example: transfer money // Transfer from one account to another double transferAmount = 500; momsSavings.withdraw(transferAmount); harrysChecking.deposit(transferAmount);  Example: add interest double interestRate = 5; // 5 percent interest double interestAmount = momsSavings.getBalance() * interestRate / 100; momsSavings.deposit(interestAmount);  Programmers use objects of the BankAccount class to carry out meaningful tasks • without knowing HOW the BankAccount objects store their data • without knowing HOW the BankAccount methods do their work
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 Commenting the Public Interface – Documenting a Method  Start the comment with a /**.  Describe the method’s purpose.  Describe each parameter: • start with @param • name of the parameter that holds the argument • a short explanation of the argument  Describe the return value: • start with @return • describe the return value  Omit @param tag for methods that have no arguments.  Omit the @return tag for methods whose return type is void.  End with */.
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Commenting the Public Interface – Documenting a Method  Example: /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { implementation—filled in later }
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 Commenting the Public Interface – Documenting a Method  Example: /** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { implementation—filled in later }
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Commenting the Public Interface – Documenting a Class  Place above the class declaration.  Supply a brief comment explaining the class's purpose.  Example: /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { . . . }  Provide documentation comments for: • every class • every method • every parameter variable • every return value
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 Method Summary Figure 3 A Method Summary Generated by javadoc
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 Method Details Figure 4 Method Detail Generated by javadoc
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 Self Check 3.6 How can you use the methods of the public interface to empty the harrysChecking bank account? Answer: harrysChecking.withdraw(harrysChecking.getBalance())
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 Self Check 3.7 What is wrong with this sequence of statements? BankAccount harrysChecking = new BankAccount(10000); System.out.println(harrysChecking.withdraw(500)); Answer: The withdraw method has return type void. It doesn’t return a value. Use the getBalance method to obtain the balance after the withdrawal.
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 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? Answer: Add an accountNumber parameter to the constructors, and add a getAccountNumber method. There is no need for a setAccountNumber method – the account number never changes after construction.
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 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) Answer: /** Constructs a new bank account with a given initial balance. @param accountNumber the account number for this account @param initialBalance the initial balance for this account */
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 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() Answer: The first sentence of the method description should describe the method—it is displayed in isolation in the summary table.
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Providing the Class Implementation  The implementation of a class consists of: • instance variables • the bodies of constructors • the bodies of methods.
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Providing Instance Variables  Determine the data that each bank account object contains.  What does the object need to remember so that it can carry out its methods?  Each bank account object only needs to store the current balance.  BankAccount instance variable declaration: public class BankAccount { private double balance; // Methods and constructors below . . . }
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Providing 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.
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Providing Constructors  Constructor's job is to initialize the instance variables of the object.  The no-argument constructor sets the balance to zero. public BankAccount() { balance = 0; }  The second constructor sets the balance to the value supplied as the construction argument. public BankAccount(double initialBalance) { balance = initialBalance; }
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Providing Constructors - Tracing the Statement Steps carried out when the following statement is executed: BankAccount harrysChecking = new BankAccount(1000);  Create a new object of type BankAccount.  Call the second constructor • because an argument is supplied in the constructor call  Set the parameter variable initialBalance to 1000.  Set the balance instance variable of the newly created object to initialBalance.  Return an object reference, that is, the memory location of the object.  Store that object reference in the harrysChecking variable.
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 Providing Constructors - Tracing the Statement Figure 5 How a Constructor Works
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 Providing Constructors A constructor is like a set of assembly instructions for an object.
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 Providing Methods  Is the method an accessor or a mutator • Mutator method • Update the instance variables in some way • Accessor method • Retrieves or computes a result  deposit method - a mutator method • Updates the balance public void deposit(double amount) { balance = balance + amount; }
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 Providing Methods  withdraw method - another mutator public void withdraw(double amount) { balance = balance – amount; }  getBalance method - an accessor method • Returns a value public double getBalance() { return balance; }
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 Table 1 Implementing Classes
  • 53. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 section_3/BankAccount.java 1 /** 2 A bank account has a balance that can be changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6 { 7 private double balance; 8 9 /** 10 Constructs a bank account with a zero balance. 11 */ 12 public BankAccount() 13 { 14 balance = 0; 15 } 16 17 /** 18 Constructs a bank account with a given balance. 19 @param initialBalance the initial balance 20 */ 21 public BankAccount(double initialBalance) 22 { 23 balance = initialBalance; 24 } 25 Continued
  • 54. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 section_3/BankAccount.java 26 /** 27 Deposits money into the bank account. 28 @param amount the amount to deposit 29 */ 30 public void deposit(double amount) 31 { 32 balance = balance + amount; 33 } 34 35 /** 36 Withdraws money from the bank account. 37 @param amount the amount to withdraw 38 */ 39 public void withdraw(double amount) 40 { 41 balance = balance - amount; 42 } 43 44 /** 45 Gets the current balance of the bank account. 46 @return the current balance 47 */ 48 public double getBalance() 49 { 50 return balance; 51 } 52 }
  • 55. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 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? Answer: An instance variable needs to be added to the class: private int accountNumber;
  • 56. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 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; } } Answer: Because the balance instance variable is accessed from the main method of BankRobber. The compiler will report an error because main has no access to BankAccount instance variables.
  • 57. Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 Self Check 3.13 The Rectangle class has four instance variables: x, y, width, and height. Give a possible implementation of the getWidth method. Answer: public int getWidth() { return width; }
  • 58. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 Self Check 3.14 Give a possible implementation of the translate method of the Rectangle class. Answer: There is more than one correct answer. One possible implementation is as follows: public void translate(int dx, int dy) { int newx = x + dx; x = newx; int newy = y + dy; y = newy; }
  • 59. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 Unit Testing  BankAccount.java can not be executed: • It has no main method • Most classes do not have a main method  Before using BankAccount.java in a larger program: • You should test in isolation  Unit test: verifies that a class works correctly in isolation, outside a complete program.
  • 60. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 Unit Testing  To test a class, either • use an environment for interactive testing, or • write a tester class to execute test instructions.  Tester class: a class with a main method that contains statements to test another class.  Typically carries out the following steps: 1. Construct one or more objects of the class that is being tested 2. Invoke one or more methods 3. Print out one or more results 4. Print the expected results
  • 61. Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 Unit Testing An engineer tests a part in isolation. This is an example of unit testing.
  • 62. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 Unit Testing with BlueJ Figure 6 The Return Value of the getBalance Method in BlueJ
  • 63. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 section_4/BankAccountTester.java 1 /** 2 A class to test the BankAccount class. 3 */ 4 public class BankAccountTester 5 { 6 /** 7 Tests the methods of the BankAccount class. 8 @param args not used 9 */ 10 public static void main(String[] args) 11 { 12 BankAccount harrysChecking = new BankAccount(); 13 harrysChecking.deposit(2000); 14 harrysChecking.withdraw(500); 15 System.out.println(harrysChecking.getBalance()); 16 System.out.println("Expected: 1500"); 17 } 18 } Program Run: 1500 Expected: 1500
  • 64. Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 Unit Testing – Building a Program  To produce a program: combine both BankAccount and BankAccountTester classes.  Details for building the program vary.  In most environments, you need to carry out these steps: 1. Make a new subfolder for your program 2. Make two files, one for each class 3. Compile both files 4. Run the test program  BankAccount and BankAccountTest have entirely different purposes: • BankAccount class describes objects that compute bank balances • BankAccountTester class runs tests that put a BankAccount object through its paces
  • 65. Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 Self Check 3.15 When you run the BankAccountTester program, how many objects of class BankAccount are constructed? How many objects of type BankAccountTester? Answer: One BankAccount object, no BankAccountTester object. The purpose of the BankAccountTester class is merely to hold the main method.
  • 66. Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 Self Check 3.16 Why is the BankAccountTester class unnecessary in development environments that allow interactive testing, such as BlueJ? Answer: In those environments, you can issue interactive commands to construct BankAccount objects, invoke methods, and display their return values.
  • 67. Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 Problem Solving: Tracing Objects  Important skill: the ability to simulate the actions of a program with pencil and paper.  Use an index card or a sticky note for each object: • Write the methods on the front • Make a table for the values of the instance variables on the back  CashRegister class
  • 68. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 Problem Solving: Tracing Objects  When an object is constructed, fill in the initial values of the instance variables.
  • 69. Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Problem Solving: Tracing Objects  Update the values of the instance variables when a mutator method is called.  After a call to cashRegister's recordPurchase method
  • 70. Copyright © 2014 by John Wiley & Sons. All rights reserved. 70 Problem Solving: Tracing Objects  More than one object: create multiple cards
  • 71. Copyright © 2014 by John Wiley & Sons. All rights reserved. 71 Problem Solving: Tracing Objects  Useful when enhancing a class.  Enhance CashRegister class to compute the sales tax.  Add methods recordTaxablePurchase and getSalesTax to the front of the card.  Don’t have enough information to compute sales tax: • need tax rate • need total of the taxable items  Need additional instance variables for: • taxRate • taxablePurchase
  • 72. Copyright © 2014 by John Wiley & Sons. All rights reserved. 72 Problem Solving: Tracing Objects  Example: CashRegister class enhancement • The code: CashRegister reg3(7.5); // 7.5 percent sales tax reg3.recordPurchase(3.95); // Not taxable reg3.recordTaxablePurchase(19.95); // Taxable • The card:
  • 73. Copyright © 2014 by John Wiley & Sons. All rights reserved. 73 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. Answer:
  • 74. Copyright © 2014 by John Wiley & Sons. All rights reserved. 74 Self Check 3.18 Trace the following method calls: Car myCar(25); myCar.addGas(20); myCar.drive(100); myCar.drive(200); myCar.addGas(5); Answer:
  • 75. Copyright © 2014 by John Wiley & Sons. All rights reserved. 75 Self Check 3.19 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. Answer:
  • 76. Copyright © 2014 by John Wiley & Sons. All rights reserved. 76 Self Check 3.20 Trace the methods of Self Check 18, updating the instance variable that you added in Self Check 19. Answer:
  • 77. Copyright © 2014 by John Wiley & Sons. All rights reserved. 77 Local Variables  Local variables are declared in the body of a method: public double giveChange() { double change = payment – purchase; purchase = 0; payment = 0; return change; }  When a method exits, its local variables are removed.  Parameter variables are declared in the header of a method: public void enterPayment(double amount)
  • 78. Copyright © 2014 by John Wiley & Sons. All rights reserved. 78 Local Variables  Local and parameter variables belong to methods: • When a method runs, its local and parameter variables come to life • When the method exits, they are removed immediately  Instance variables belong to objects, not methods: • When an object is constructed, its instance variables are created • The instance variables stay alive until no method uses the object any longer  Instance variables are initialized to a default value: • Numbers are initialized to 0 • Object references are set to a special value called null • A null object reference refers to no object at all  You must initialize local variables: • The compiler complains if you do not
  • 79. Copyright © 2014 by John Wiley & Sons. All rights reserved. 79 Self Check 3.21 What do local variables and parameter variables have in common? In which essential aspect do they differ? Answer: Variables of both categories belong to methods – they come alive when the method is called, and they die when the method exits. They differ in their initialization. Parameter variables are initialized with the call values; local variables must be explicitly initialized.
  • 80. Copyright © 2014 by John Wiley & Sons. All rights reserved. 80 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; Answer: After computing the change due, payment and purchase were set to zero. If the method returned payment - purchase, it would always return zero.
  • 81. Copyright © 2014 by John Wiley & Sons. All rights reserved. 81 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. Answer:
  • 82. Copyright © 2014 by John Wiley & Sons. All rights reserved. 82 The this Reference  Two types of inputs are passed when a method is called: • The object on which you invoke the method • The method arguments  In the call momsSavings.deposit(500) the method needs to know: • The account object (momsSavings) • The amount being deposited (500)  The implicit parameter of a method is the object on which the method is invoked.  All other parameter variables are called explicit parameters.
  • 83. Copyright © 2014 by John Wiley & Sons. All rights reserved. 83 The this Reference  Look at this method: public void deposit(double amount) { balance = balance + amount; } • amount is the explicit parameter • The implicit parameter(momSavings) is not seen • balance means momSavings.balance  When you refer to an instance variable inside a method, it means the instance variable of the implicit parameter.
  • 84. Copyright © 2014 by John Wiley & Sons. All rights reserved. 84 The this Reference  The this reference denotes the implicit parameter balance = balance + amount; actually means this.balance = this.balance + amount;  When you refer to an instance variable in a method, the compiler automatically applies it to the this reference.
  • 85. Copyright © 2014 by John Wiley & Sons. All rights reserved. 85 The this Reference  Some programmers feel that inserting the this reference before every instance variable reference makes the code clearer: public BankAccount(double initialBalance) { this.balance = initialBalance; }
  • 86. Copyright © 2014 by John Wiley & Sons. All rights reserved. 86 The this Reference Figure 7 The Implicit Parameter of a Method Call
  • 87. Copyright © 2014 by John Wiley & Sons. All rights reserved. 87 The this Reference  The this reference can be used to distinguish between instance variables and local or parameter variables: public BankAccount(double balance) { this.balance = balance; }  A local variable shadows an instance variable with the same name. • You can access the instance variable name through the this reference. Code Defensively: Avoid hard to find bugs!!
  • 88. Copyright © 2014 by John Wiley & Sons. All rights reserved. 88 The this Reference  In Java, local and parameter variables are considered first when looking up variable names.  Statement this.balance = balance; means: “Set the instance variable balance to the parameter variable balance”.
  • 89. Copyright © 2014 by John Wiley & Sons. All rights reserved. 89 The this Reference  A method call without an implicit parameter is applied to the same object.  Example: public class BankAccount { . . . public void monthlyFee() { withdraw(10); // Withdraw $10 from this account } }  The implicit parameter of the withdraw method is the (invisible) implicit parameter of the monthlyFee method
  • 90. Copyright © 2014 by John Wiley & Sons. All rights reserved. 90 The this Reference  You can use the this reference to make the method easier to read: public class BankAccount { . . . public void monthlyFee() { this.withdraw(10); // Withdraw $10 from this account } }
  • 91. Copyright © 2014 by John Wiley & Sons. All rights reserved. 91 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? Answer: One implicit parameter, called this, of type BankAccount, and one explicit parameter, called amount, of type double.
  • 92. Copyright © 2014 by John Wiley & Sons. All rights reserved. 92 Self Check 3.25 In the deposit method, what is the meaning of this.amount? Or, if the expression has no meaning, why not? Answer: It is not a legal expression. this is of type BankAccount and the BankAccount class has no instance variable named amount.
  • 93. Copyright © 2014 by John Wiley & Sons. All rights reserved. 93 Self Check 3.26 How many implicit and explicit parameters does the main method of the BankAccountTester class have, and what are they called? Answer: No implicit parameter — the main method is not invoked on any object — and one explicit parameter, called args.
  • 94. Copyright © 2014 by John Wiley & Sons. All rights reserved. 94 Shape Classes  Good practice: Make a class for each part of a drawing that occurs more than once. public class Car { public Car(int x, int y) { // Remember position . . . } public void draw(Graphics2D g2) { // Drawing instructions . . . } }
  • 95. Copyright © 2014 by John Wiley & Sons. All rights reserved. 95 Drawing Cars Goal: draw two cars - one in top-left corner of window, and another in the bottom right. Figure 8 The Car Component Draws Two Car Shapes
  • 96. Copyright © 2014 by John Wiley & Sons. All rights reserved. 96 Plan Complex Shapes on Graph Paper Figure 9 Using Graph Paper to Find Shape Coordinates
  • 97. Copyright © 2014 by John Wiley & Sons. All rights reserved. 97 Drawing Cars The program that produces the drawing is composed of three classes:  The Car class is responsible for drawing a single car. • Two objects of this class are constructed, one for each car.  The CarComponent class displays the drawing  The CarViewer class shows a frame that contains a CarComponent
  • 98. Copyright © 2014 by John Wiley & Sons. All rights reserved. 98 Drawing Cars  The paintComponent method of the CarComponent class draws the two cars.  To compute bottom right position: Car car1 = new Car(0, 0); int x = getWidth() – 60; int y = getHeight() – 30; Car car2 = new Car(x, y); • getWidth and getHeight return the dimensions of the CarComponent • Subtract the dimensions of the car to determine the position of car2  When window is resized paintComponent is called  Car position is recomputed using current dimensions
  • 99. Copyright © 2014 by John Wiley & Sons. All rights reserved. 99 section_8/Car.java 1 import java.awt.Graphics2D; 2 import java.awt.Rectangle; 3 import java.awt.geom.Ellipse2D; 4 import java.awt.geom.Line2D; 5 import java.awt.geom.Point2D; 6 7 /** 8 A car shape that can be positioned anywhere on the screen. 9 */ 10 public class Car 11 { 12 private int xLeft; 13 private int yTop; 14 15 /** 16 Constructs a car with a given top left corner. 17 @param x the x coordinate of the top left corner 18 @param y the y coordinate of the top left corner 19 */ 20 public Car(int x, int y) 21 { 22 xLeft = x; 23 yTop = y; 24 } 25 Continued
  • 100. Copyright © 2014 by John Wiley & Sons. All rights reserved. 100 section_8/Car.java 26 /** 27 Draws the car. 28 @param g2 the graphics context 29 */ 30 public void draw(Graphics2D g2) 31 { 32 Rectangle body = new Rectangle(xLeft, yTop + 10, 60, 10); 33 Ellipse2D.Double frontTire 34 = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10); 35 Ellipse2D.Double rearTire 36 = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10); 37 38 // The bottom of the front windshield 39 Point2D.Double r1 = new Point2D.Double(xLeft + 10, yTop + 10); 40 // The front of the roof 41 Point2D.Double r2 = new Point2D.Double(xLeft + 20, yTop); 42 // The rear of the roof 43 Point2D.Double r3 = new Point2D.Double(xLeft + 40, yTop); 44 // The bottom of the rear windshield 45 Point2D.Double r4 = new Point2D.Double(xLeft + 50, yTop + 10); 46 Continued
  • 101. Copyright © 2014 by John Wiley & Sons. All rights reserved. 101 section_8/Car.java 47 Line2D.Double frontWindshield = new Line2D.Double(r1, r2); 48 Line2D.Double roofTop = new Line2D.Double(r2, r3); 49 Line2D.Double rearWindshield = new Line2D.Double(r3, r4); 50 51 g2.draw(body); 52 g2.draw(frontTire); 53 g2.draw(rearTire); 54 g2.draw(frontWindshield); 55 g2.draw(roofTop); 56 g2.draw(rearWindshield); 57 } 58 }
  • 102. Copyright © 2014 by John Wiley & Sons. All rights reserved. 102 section_8/CarComponent.java 1 import java.awt.Graphics; 2 import java.awt.Graphics2D; 3 import javax.swing.JComponent; 4 5 /** 6 This component draws two car shapes. 7 */ 8 public class CarComponent extends JComponent 9 { 10 public void paintComponent(Graphics g) 11 { 12 Graphics2D g2 = (Graphics2D) g; 13 14 Car car1 = new Car(0, 0); 15 16 int x = getWidth() - 60; 17 int y = getHeight() - 30; 18 19 Car car2 = new Car(x, y); 20 21 car1.draw(g2); 22 car2.draw(g2); 23 } 24 }
  • 103. Copyright © 2014 by John Wiley & Sons. All rights reserved. 103 section_8/CarViewer.java 1 import javax.swing.JFrame; 2 3 public class CarViewer 4 { 5 public static void main(String[] args) 6 { 7 JFrame frame = new JFrame(); 8 9 frame.setSize(300, 400); 10 frame.setTitle("Two cars"); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 13 CarComponent component = new CarComponent(); 14 frame.add(component); 15 16 frame.setVisible(true); 17 } 18 }
  • 104. Copyright © 2014 by John Wiley & Sons. All rights reserved. 104 UML Class Diagrams: Arrow Types
  • 105. Copyright © 2014 by John Wiley & Sons. All rights reserved. 105 UML Class Diagrams JComponent CarComponent JFrame Car Can you figure out which arrows reflect the relationships among these classes?
  • 106. Copyright © 2014 by John Wiley & Sons. All rights reserved. 106 Self Check 3.27 Which class needs to be modified to have the two cars positioned next to each other? Answer: CarComponent
  • 107. Copyright © 2014 by John Wiley & Sons. All rights reserved. 107 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? Answer: In the draw method of the Car class, call g2.fill(frontTire); g2.fill(rearTire);
  • 108. Copyright © 2014 by John Wiley & Sons. All rights reserved. 108 Self Check 3.29 How do you make the cars twice as big? Answer: Double all measurements in the draw method of the Car class.