Vous êtes sur la page 1sur 95

This watermark does not appear in the registered version - http://www.clicktoconvert.

com

Defining Your Own Classes


Part 3

Template for Class Definition


Import Statements

Class Comment

class

Class Name

Data Members

Methods
(incl. Constructor)

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Data Member Declaration

<modifiers>

<data type> <name> ;

Modifiers

Data Type

private

String

Name

ownerName ;

Note: Theres only one modifier in this


example.

Method Declaration
<modifier>

<return type>

<method name>

( <parameters>

<statements>
}

Modifier

public

Return Type

void

setOwnerName

ownerName = name;
}

Method Name

Parameter

String

name

Statements

) {

){

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Constructor

A constructor is a special method that is executed when a new


instance of the class is created.

public <class name> ( <parameters> ){


<statements>
}
Modifier

Class Name

public

Parameter

Bicycle

) {

ownerName = "Unassigned";
}

Statements

First Example: Using the Bicycle Class


class BicycleRegistration {
public static void main(String[]

args) {

Bicycle bike1, bike2;


String

owner1, owner2;

bike1 = new Bicycle( ) ;

//Create and assign values to bike1

bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ) ;

//Create and assign values to bike2

bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( ) ; //Output the information
owner2 = bike2.getOwnerName( ) ;

}
}

System.out.println(owner1

+ " owns a bicycle.");

System.out.println(owner2

+ " also owns a bicycle.");

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Definition of the Bicycle Class


class Bicycle {
// Data Member
private String ownerName;
//Constructor: Initialzes the data member
public void Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
}

Multiple Instances
Once the Bicycle class is defined, we can create
multiple instances.
bike1

bike2

Bicycle bike1, bike2;


bike1 = new Bicycle( );
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( );
bike2.setOwnerName("Ben Jones");

Sample Code

: Bicycle
ownerName
Adam Smith

: Bicycle
ownerName
Ben Jones

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Program Structure and Source


Files
BicycleRegistration

Bicycle

There are two source files.


Each class definition is
stored in a separate file.
BicycleRegistration.java

Bicycle.java

To run the program: 1. javac Bicycle.java


(compile)
2. javac BicycleRegistration.java (compile)
3. java BicycleRegistration
(run)

Class Diagram for Bicycle

Bicycle
- String ownerName
+ Bicycle( )
+ getOwnerName( )
+ setOwnerName(String)

Method Listing
We list the name and the
data type of an argument
passed to the method.

public plus symbol (+)


private minus symbol (-)

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Account Class


class Account {
private String ownerName;

public void setInitialBalance


(double bal) {

private double balance;


balance = bal;
public Account( ) {
ownerName = "Unassigned";
balance = 0.0;
}

}
public void setOwnerName
(String name) {

public void add(double amt) {


balance = balance + amt;
}

ownerName = name;
}
}

public void deduct(double amt) {


balance = balance - amt;
}
public double getCurrentBalance( ) {
return balance;
}
public String getOwnerName( ) {
return ownerName;
}

Page 1

Page 2

Second Example: Using Bicycle and Account


class SecondMain

//This sample program uses both the Bicycle and Account classes
public static void main(String[]

args) {

Bicycle bike;
Account acct;
String

myName = "Jon Java";

bike = new Bicycle( );


bike.setOwnerName(myName);
acct = new Account( );
acct.setOwnerName(myName);
acct.setInitialBalance(250.00);
acct.add(25.00);
acct.deduct(50);
//Output some information
System.out.println(bike.getOwnerName() + " owns a bicycle and");
System.out.println("has $ " + acct.getCurrentBalance() +
" left in the bank");
}
}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Program Structure for SecondMain


Bicycle
SecondMain
Account

SecondMain.java

Bicycle.java

Account.java

To run the program: 1. javac Bicycle.java


2. javac Account.java
2. javac SecondMain.java
3. java SecondMain

(compile)
(compile)
(compile)
(run)

Note: You only


need to compile
the class once.
Recompile only
when you made
changes in the
code.

Arguments and Parameters


class Sample {

class Account {

public static void


main(String[] arg) {
Account acct = new Account();
. . .

public void add(double amt) {

acct.add(400);
. . .

}
. . .
}

parameter

. . .

balance = balance + amt;


. . .
}

argument

An argument is a value we pass to a method


A parameter is a placeholder in the called method
to hold the value of the passed argument.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Matching Arguments and Parameters

The number or
arguments and the
parameters must be
the same

Arguments and
parameters are
paired left to right

The matched pair


must be assignmentcompatible (e.g. you
cannot pass a double
argument to a int
parameter)

Demo demo = new Demo( );


int i = 5; int k = 14;
demo.compute(i, k, 20);

3 arguments

Passing Side

class Demo {
public void compute(int i, int j, double x) {
. . .
}

3 parameters

Receiving Side

Memory Allocation

14

14

20

20.0

Passing Side
Literal constant
has no name

Receiving Side

Separate memory
space is allocated
for the receiving
method.

Values of
arguments are
passed into
memory allocated
for parameters.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Information Hiding and Visibility Modifiers


The modifiers public and private designate the
accessibility of data members and methods.
If a class component (data member or method) is
declared private, client classes cannot access it.
If a class component is declared public, client
classes can access it.
Internal details of a class are declared private and
hidden from the clients. This is information hiding.

Accessibility Example

Service obj = new Service();

class Service {
public int memberOne;
private int memberTwo;
public void doOne() {

obj.memberOne = 10;

obj.memberTwo = 20;

}
private void doTwo() {

obj.doOne();

obj.doTwo();
}

Client

Service

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Data Members Should Be private


Data members are the implementation details of
the class, so they should be invisible to the clients.
Declare them private .
Exception: Constants can (should) be declared
public if they are meant to be used directly by the
outside methods.

Guideline for Visibility Modifiers


Guidelines in determining the visibility of data
members and methods:
Declare the class and instance variables private.
Declare the class and instance methods private if they
are used only by the other methods in the same class.
Declare the class constants public if you want to make
their values directly readable by the client programs. If
the class constants are used for internal purposes only,
then declare them private.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Diagram Notation for Visibility

public plus symbol (+)


private minus symbol (-)

Class Constants
In Chapter 3, we introduced the use of constants.
We illustrate the use of constants in programmerdefined service classes here.
Remember, the use of constants
provides a meaningful description of what the values
stand for. number = UNDEFINED; is more meaningful
than number = -1;
provides easier program maintenance. We only need to
change the value in the constant declaration instead of
locating all occurrences of the same value in the
program code

This watermark does not appear in the registered version - http://www.clicktoconvert.com

A Sample Use of Constants


class Dice {
private static final int MAX_NUMBER = 6;
private static final int MIN_NUMBER = 1;
private static final int NO_NUMBER = 0;
private int number;
public Dice( ) {
number = NO_NUMBER;
}
//Rolls the dice
public void roll( ) {
number = (int) (Math.floor(
(Math.random() *
(MAX_NUMBER - MIN_NUMBER + 1)
)) + MIN_NUMBER);
}
//Returns the number on this dice
public int getNumber( ) {
return number;
}
}

Local Variables
Local variables are declared within a method
declaration and used for temporary services, such
as storing intermediate computation results.
public double convert(int num) {
double result;

local variable

result = Math.sqrt(num * num);


return result;
}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Local, Parameter & Data Member

An identifier appearing inside a method can be a


local variable, a parameter, or a data member.
The rules are
If theres a matching local variable declaration or a
parameter, then the identifier refers to the local variable
or the parameter.
Otherwise, if theres a matching data member
declaration, then the identifier refers to the data
member.
Otherwise, it is an error because theres no matching
declaration.

Sample Matching
class MusicCD {
private String
private String
private String

artist;
title;
id;

public MusicCD(String name1, String name2) {


String ident;
artist = name1;
title

= name2;

ident

= artist.substring(0,2) + "-" +
title.substring(0,9);

id
}
...
}

= ident;

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Calling Methods of the Same Class


So far, we have been calling a method of another class
(object).
It is possible to call method of a class from another method
of the same class.
in this case, we simply refer to a method without dot notation

Changing Any Class to a Main Class


Any class can be set to be a main class.
All you have to do is to include the main method.
class Bicycle {
//definition of the class as shown before comes here
//The main method that shows a sample
//use of the Bicycle class
public static void main(String[] args) {
Bicycle myBike;
myBike = new Bicycle( );
myBike.setOwnerName("Jon Java");
System.out.println(myBike.getOwnerName() + "owns a bicycle");
}
}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Methods: A Deeper
Look
2005 Pearson Education, Inc. All rights reserved.

Object-oriented approach to modular design

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Notes on Declaring and Using Methods

Three ways to call a method:


1. Use a method name by itself to call another method of the
same class
double result = maximum( number1, number2, number3 );
2- Use a variable containing a reference to an object, followed
by a dot (.) and the method name to call a method of the
referenced object
maximumFinder.determineMaximum();
3- Use the class name and a dot (.) to call a static method of
a class
ClassName.methodName( arguments )

static methods cannot call non-static


methods of the same class directly
2005 Pearson Education, Inc. All rights reserved.

Notes on Declaring and Using Methods


(Cont.)
Three ways to return control to the calling
statement:
If method does not return a result: (void)
Program flow reaches the method-ending right brace } or
Program executes the statement return;

If method does return a result:


Program executes the statement return expression;
expression is first evaluated and then its value is
returned to the caller

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Declaring Methods with Multiple


Parameters
Multiple parameters can be declared by
specifying a comma-separated list.
Arguments passed in a method call must be consistent with
the number
number, types and order of the parameters
Sometimes called formal parameters
Demo demo = new Demo( );
int i = 5; int k = 14;
demo.compute(i, k, 20);

class Demo {
public void compute(int i, int j, double x) {
. . .
}
}
2005 Pearson Education, Inc. All rights reserved.

The number or
arguments and the
parameters must be the
same

Demo demo = new Demo( );


int i = 5; int k = 14;
demo.compute(i, k, 20);

3 arguments

Passing Side

class Demo {
public void compute(int i, int j, double x) {
. . .
}
}

3 parameters

Receiving Side

Arguments and
parameters are
paired left to right

The matched pair


must be assignmentcompatible (e.g. you
cannot pass a double
argument to a int
parameter)

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

1
2
3
4
5
6
7
8
9
10

// MaximumFinder.java
// Programmer-declared method maximum.
import java.util.Scanner;

Outline

public class MaximumFinder


{
// obtain three floating-point values and locate the maximum value
public void determineMaximum()

MaximumFinder.java

// create Scanner for input from command window

11
12
13
14
15
16
17
18
19
20
21

Scanner input = new Scanner( System.in );

Prompt the user to enter


three double

and read
// obtain user input
System.out.print(
values
"Enter three floating-point values separated by spaces: " );
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum( number1, number2, number3 );

22
23
24
25

(1 of 2)

Call method
maximum

// display maximum value


System.out.println( "Maximum is: " + result );
} // end method determineMaximum

26

Display maximum
value

2005 Pearson Education, Inc. All rights reserved.

27

// returns the maximum of its three double parameters

28

public double maximum( double x, double y, double z )

29

30

Outline

Declare the maximum


method
double maximumValue = x; // assume x is the largest to start

31
32

// determine whether y is greater than maximumValue

33

if ( y > maximumValue )

34

maximumValue = y;

35

Maximum
Finder.java

Compare y and
(2 of 2)
maximumValue

36

// determine whether z is greater than maximumValue

37

if ( z > maximumValue )

38

maximumValue = z;

Compare z and
maximumValue

39
40

return maximumValue;

41

} // end method maximum

Return the maximum


value

42 } // end class MaximumFinder

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

//

// Application to test class MaximumFinder.

MaximumFinderTest.java

3
4

public class MaximumFinderTest

// application starting point

public static void main( String args[] )

9
10
11

Create a MaximumFinder
object

Outline
MaximumFinderTest
.java

MaximumFinder maximumFinder = new MaximumFinder();

Call the determineMaximum


method

maximumFinder.determineMaximum();
} // end main

12 } // end class MaximumFinderTest


Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

Enter three floating-point values separated by spaces: 5.8 12.45 8.32


Maximum is: 12.45

Enter three floating-point values separated by spaces: 6.46 4.12 10.54


Maximum is: 10.54

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error


Declaring method parameters of the same
type as float x, y is a syntax error
instead of
float x, float y
-a type is required for each parameter in the
parameter list.

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Call-by-Value Parameter Passing

When a method is called,


the value of the argument is passed to the matching
parameter, and
separate memory space is allocated to store this value.

This way of passing the value of arguments is called


a pass-by-value or call-by-value scheme.
Since separate memory space is allocated for each
parameter during the execution of the method,
the parameter is local to the method, and therefore
changes made to the parameter will not affect the value of
the corresponding argument.
th Inc. All rights reserved.
2005 Pearson Education,

4 Ed Chapter
7 - 39

Call-by-Value Example
class Tester {
public void myMethod(int one, double two ) {
one = 25;
two = 35.4;
}
}

Tester tester;
int x, y;
tester = new Tester();
x = 10;
y = 20;
tester.myMethod(x , y );
System.out.println(x + " " + y);

10 20
produces

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Memory Allocation for Parameters

4th Ed Chapter 7 - 41

Memory Allocation for Parameters (cont'd)

4th Ed Chapter 7 - 42

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Passing Objects to a Method


As we can pass int and double values, we can also
pass an object to a method.
When we pass an object, we are actually passing
the reference (name) of an object
it means a duplicate of an object is NOT created in the
called method

2005 Pearson Education, Inc. All rights reserved.

Passing a Student Object


1

student

LibraryCard card2;

st

card2 = new LibraryCard();


card2.setOwner(student);

card2

Passing Side

class LibraryCard {
private Student owner;
public void setOwner(Student st) {
owner = st;
}

: LibraryCard

: Student

owner

name

Receiving Side

Jon Java
borrowCnt

Argument is passed

Value is assigned to the


data member

email
jj@javauniv.edu

State of Memory

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Sharing an Object

We pass the same Student


object to card1 and card2

Since we are actually passing


a reference to the same
object, it results in owner of
two LibraryCard objects
pointing to the same Student
object

2005 Pearson Education, Inc. All rights reserved.

Returning an Object from a Method

As we can return a primitive data value


from a method, we can return an object
from a method also.
We return an object from a method, we are
actually returning a reference (or an
address) of an object.
This means we are not returning a copy of an object,
but only the reference of this object

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Object-Returning Method
Here's a sample method that returns an object:
Return type indicates
the class of an object
we're returning from
the method.

public Fraction simplify( ) {


Fraction simp;

gcd method Return


the Greatest Number
Divisor

int num
= getNumberator();
int denom = getDenominator();
int gcd
= gcd(num, denom);
simp = new Fraction(num/gcd, denom/gcd);
return simp;
}

Return an instance of
the Fraction class

2005 Pearson Education, Inc. All rights reserved.

A Sample Call to simplify


public Fraction simplify( ) {
int num
= getNumerator();
int denom = getDenominator();
int gcd
= gcd(num, denom);

f1 = new Fraction(24, 36);

Fraction simp = new


Fraction(num/gcd,
denom/gcd);

f2 = f1.simplify();

return simp;
}

f1
simp
f2

: Fraction

: Fraction

numerator
24

numerator
2

denominator
36

denominator
3

This watermark does not appear in the registered version - http://www.clicktoconvert.com

A Sample Call to simplify (cont'd)


public Fraction simplify( ) {
f1 = new Fraction(24,

int num
= getNumerator();
int denom = getDenominator();
int gcd
= gcd(num, denom);

26);

f2 = f1.simplify();
Fraction simp = new
Fraction(num/gcd,
denom/gcd);
return simp;
}

f1

simp

f2

: Fraction
numerator
24
denominator
36

: Fraction
: Fraction
numerator
numerator
2
2
denominator
denominator
3
3

The value of simp, which


is a reference, is returned
and assigned to f2.

4th Ed Chapter 7 - 49

static Methods, static Fields and


Class Math
static method (or class method)
Call a static method by using the method call:
ClassName.methodName( arguments )
All methods of the Math class are static
example: Math.sqrt( 900.0 )

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Software Engineering Observation


Class Math is part of the java.lang package,
which is implicitly imported by the compiler,
so it is not necessary to import class Math to
use its methods.

2005 Pearson Education, Inc. All rights reserved.

static Methods, static Fields and


Class Math (Cont.)
Constants
Keyword final
Cannot be changed after initialization

static fields (or class variables)


Are fields where one copy of the variable is shared among
all objects of the class

Math.PI and Math.E are final static fields


of the Math class

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Method

Description

Example

abs( x )

absolute value of x

ceil( x )

rounds x to the smallest integer not


less than x

abs( 23.7 ) is 23.7


abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0

cos( x )

trigonometric cosine of x (x in radians)

cos( 0.0 ) is 1.0

exp( x )

exponential method ex

exp( 1.0 ) is 2.71828


exp( 2.0 ) is 7.38906

floor( x )

rounds x to the largest integer not greater Floor( 9.2 ) is 9.0


than x
floor( -9.8 ) is -10.0

log( x )

natural logarithm of x (base e)

log( Math.E ) is 1.0


log( Math.E * Math.E ) is 2.0

max( x, y ) larger value of x and y

max( 2.3, 12.7 ) is 12.7


max( -2.3, -12.7 ) is -2.3

min( x, y ) smaller value of x and y

min( 2.3, 12.7 ) is 2.3


min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to the power y (i.e., xy)

pow( 2.0, 7.0 ) is 128.0


pow( 9.0, 0.5 ) is 3.0

sin( x )

trigonometric sine of x (x in radians)

sin( 0.0 ) is 0.0

sqrt( x )

square root of x

sqrt( 900.0 ) is 30.0

tan( x )

trigonometric tangent of x (x in radians)

tan( 0.0 ) is 0.0

Math class methods.


2005 Pearson Education, Inc. All rights reserved.

static Methods, static Fields and


Class Math (Cont.)
Method main
main is declared static so it can be invoked without
creating an object of the class containing main
Any class can contain a main method
The JVM invokes the main method belonging to the class
specified by the first command-line argument to the java
command

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Reusing method Math.max


The expression Math.max( x, Math.max( y, z ) )
determines the maximum of y and z, and then determines the
maximum of x and that value

String concatenation
Using the + operator with two Strings concatenates them into a
new String

Ex:

ident

= artist.substring
artist.substring(
( 0,2 ) + " - " + title.substring
title.substring(
( 0,9 );

Using the + operator with a String and a value of another data


type concatenates the String with a String representation of
the other value
When the other value is an object, its toString method is called to
generate its String representation

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error


Confusing the + operator used for string concatenation with
the + operator used for addition can lead to strange results.
Java evaluates the operands of an operator from left to right.
For example, if integer variable y has the value 5 , the
expression "y + 2 = " + y + 2 results in the string
"y + 2 = 52", not "y + 2 = 7", because first the value
of y (5) is concatenated with the string "y + 2 = ", then the
value 2 is concatenated with the new larger string
"y + 2 = 5".
The expression "y + 2 = " + (y + 2) produces the
desired result "y + 2 = 7".

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Common Programming Error


Omitting the return-value-type in a method
declaration is a syntax error.

public double maximum( double x, double y, double z )

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error


Placing a semicolon after the right parenthesis enclosing the
parameter list of a method declaration is a syntax error.
public double maximum( double x, double y, double z ) ;
{

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Common Programming Error


Redeclaring a method parameter as a local
variable in the methods body is a compilation
error.
public double maximum( double x, double y, double z )
{
double y;

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error


Forgetting to return a value from a method that
should return a value is a compilation error.
If a return value type other than void is specified,
the method must contain a return statement that
returns a value consistent with the methods returnvalue-type.
Returning a value from a method whose return type
has been declared void is a compilation error.

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Method Call Stack and Activation


Records
Stacks
Last-in, first-out (LIFO) data structures
Items are pushed (inserted) onto the top
Items are popped (removed) from the top

Program execution stack


Also known as the method call stack
Return addresses of calling methods are pushed onto this
stack when they call other methods and popped off when
control returns to them

2005 Pearson Education, Inc. All rights reserved.

Method Call Stack and Activation


Records (Cont.)
A methods local variables are stored in a portion of this
stack known as the methods activation record or stack
frame
When the last variable referencing a certain object is popped
off this stack, that object is no longer accessible by the
program
Will eventually be deleted from memory during
garbage collection
Stack overflow occurs when the stack cannot allocate enough
space for a methods activation record

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Argument Promotion and Casting


Argument promotion
Java will promote a method call argument to match its
corresponding method parameter according to the
promotion rules
Values in an expression are promoted to the highest type
in the expression (a temporary copy of the value is made)
Converting values to lower types results in a compilation
error, unless the programmer explicitly forces the
error
conversion to occur
Place the desired data type in parentheses before the value
example: ( int ) 4.5

2005 Pearson Education, Inc. All rights reserved.

Type

Valid promotions

double
float
long
int
char
short
byte
boolean

None
double
float or double
long, float or double
int, long, float or double
int, long, float or double (but not char)
short, int, long, float or double (but not char)
None (boolean values are not considered to be numbers in Java)

Fig. 6.5 | Promotions allowed for primitive types.

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Common Programming Error


Converting a primitive-type value to
another primitive type may change the
value if the new type is not a valid
promotion.

2005 Pearson Education, Inc. All rights reserved.

Package

Description

java.applet

The Java Applet Package contains a class and several interfaces required to create Java
appletsprograms that execute in Web browsers. (Applets are discussed in Chapter 20,
Introduction to Java Applets; interfaces are discussed in Chapter 10, Object_-Oriented
Programming: Polymorphism.)

java.awt

The Java Abstract Window Toolkit Package contains the classes and interfaces required
to create and manipulate GUIs in Java 1.0 and 1.1. In current versions of Java, the Swing
GUI components of the javax.swing packages are often used instead. (Some elements
of the java.awt package are discussed in Chapter 11, GUI Components: Part 1,
Chapter 12, Graphics and Java2D, and Chapter 22, GUI Components: Part 2.)

java.awt.event

The Java Abstract Window Toolkit Event Package contains classes and interfaces that
enable event handling for GUI components in both the java.awt and javax.swing
packages. (You will learn more about this package in Chapter 11, GUI Components: Part
1 and Chapter 22, GUI Components: Part 2.)

java.io

The Java Input/Output Package contains classes and interfaces that enable programs to
input and output data. (You will learn more about this package in Chapter 14, Files and
Streams.)

java.lang

The Java Language Package contains classes and interfaces (discussed throughout this
text) that are required by many Java programs. This package is imported by the compiler
into all programs, so the programmer does not need to do so.

Java API packages (a subset). (Part 1 of 2)


2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Package

Description

java.net

The Java Networking Package contains classes and interfaces that enable programs to
communicate via computer networks like the Internet. (You will learn more about this in
Chapter 24, Networking.)

java.text

The Java Text Package contains classes and interfaces that enable programs to manipulate
numbers, dates, characters and strings. The package provides internationalization capabilities
that enable a program to be customized to a specific locale (e.g., a program may display strings
in different languages, based on the users country).

java.util

The Java Utilities Package contains utility classes and interfaces that enable such actions as date
and time manipulations, random-number processing (class Random), the storing and processing
of large amounts of data and the breaking of strings into smaller pieces called tokens (class
StringTokenizer). (You will learn more about the features of this package in Chapter 19,
Collections.)

javax.swing

The Java Swing GUI Components Package contains classes and interfaces for Javas Swing
GUI components that provide support for portable GUIs. (You will learn more about this
package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.)

javax.swing.event The Java Swing Event Package contains classes and interfaces that enable event handling (e.g.,
responding to button clicks) for GUI components in package javax.swing. (You will learn
more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI
Components: Part 2.)

Java API packages (a subset). (Part 2 of 2)

2005 Pearson Education, Inc. All rights reserved.

Scope of Declarations
Basic scope rules
Scope of a parameter declaration is the body of the method
in which appears
Scope of a local-variable declaration is from the point of
declaration to the end of that block
Scope of a local-variable declaration in the initialization
section of a for header is the rest of the for header and
the body of the for statement
Scope of a method or field of a class is the entire body of
the class

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Scope of Declarations (Cont.)


Shadowing
A data member is shadowed (or hidden) if a local variable
or parameter has the same name as the field
This lasts until the local variable or parameter goes out of
scope

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error


A compilation error occurs when a local variable
is declared more than once in a method.

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Error-Prevention Tip
Use different names for data members and local
variables to help prevent subtle logic errors that
occur when a method is called and a local
variable of the method shadows a field of the
same name in the class.

2005 Pearson Education, Inc. All rights reserved.

//

// Scope class demonstrates field and local variable scopes.

Scope.java

Outline

3
4

public class Scope

Scope.java

// field that is accessible to all methods of this class

private int x = 1;

(1 of 2)

8
9

// method begin creates and initializes local variable x

10

// and calls methods useLocalVariable and useField

11

public void begin()

12

13

Shadows field x

int x = 5; // method's local variable x shadows field x

14
15

System.out.printf( "local x in method begin is %d\n", x );

16

Display value of
local variable x

17

useLocalVariable(); // useLocalVariable has local x

18

useField(); // useField uses class Scope's field x

19

useLocalVariable(); // useLocalVariable reinitializes local x

20
21

useField(); // class Scope's field x retains its value

2005 Pearson
Education, Inc. All rights
reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

22

System.out.printf( "\nlocal x in method begin is %d\n", x );

23

Outline

} // end method begin

24
25

// create and initialize local variable x during each call

26

public void useLocalVariable()

27

28

Shadows field x

Scope.java

int x = 25; // initialized each time useLocalVariable is called

(2 of 2)

29
30

System.out.printf(

31

"\nlocal x on entering method useLocalVariable is %d\n", x );

32

++x; // modifies this method's local variable x

33

System.out.printf(

34

"local x before exiting method useLocalVariable is %d\n", x );

35

Display value of
local variable x

} // end method useLocalVariable

36
37

// modify class Scope's field x during each call

38

public void useField()

39

40

System.out.printf(

41

"\nfield x on entering method useField is %d\n", x );

42

x *= 10; // modifies class Scope's field x

43

System.out.printf(

44

Display value of
field x

"field x before exiting method useField is %d\n", x );

45

} // end method useField

46 } // end class Scope

2005 Pearson
Education, Inc. All rights
reserved.

// Fig. 6.12: ScopeTest.java

// Application to test class Scope.

Outline

3
4

public class ScopeTest

// application starting point

public static void main( String args[] )

9
10
11

ScopeTest.java

Scope testScope = new Scope();


testScope.begin();
} // end main

12 } // end class ScopeTest


local x in method begin is 5
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 1
field x before exiting method useField is 10
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 10
field x before exiting method useField is 100
local x in method begin is 5

2005 Pearson
Education, Inc. All rights
reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Method Overloading
Method overloading
Multiple methods with the same name, but different types,
number or order of parameters in their parameter lists
Compiler decides which method is being called by matching the
method calls argument list to one of the overloaded methods
parameter lists
A methods name and number, type and order of its parameters
form its signature

Differences in return type are irrelevant in method overloading


Overloaded methods can have different return types
Methods with different return types but the same signature cause
a compilation error

2005 Pearson Education, Inc. All rights reserved.

Overloaded Methods
Methods can share the same name as long as
they have a different number of parameters (Rule 1) or
their parameters are of different data types when the number of
parameters is the same (Rule 2)

public void myMethod(int x, int y) { ... }


public void myMethod(int x) { ... }

public void myMethod(double x) { ... }

Rule 1

Rule 2

public void myMethod(int x) { ... }

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

// Fig. 6.13: MethodOverload.java


// Overloaded method declarations.
public class MethodOverload

Outline
Correctly calls the square
of int
method
Correctly calls the square of double
method

// test overloaded square methods


public void testOverloadedMethods()
MethodOverload
{
.java
System.out.printf( "Square of integer 7 is %d\n", square( 7 ) );
System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) );
} // end method testOverloadedMethods
// square method with int argument
public int square( int intValue )
{
System.out.printf( "\nCalled square with int argument: %d\n",
intValue );
return intValue * intValue;
Declaring the square
} // end method square with int argument
Label1

of int method

// square method with double argument


public double square( double doubleValue )
{
System.out.printf( "\nCalled square with double argument: %f\n",
doubleValue );
return doubleValue * doubleValue;
Declaring the square
} // end method square with double argument
of double method
} // end class MethodOverload

2005 Pearson
Education, Inc. All rights
reserved.

1
2
3
4
5
6
7
8
9
10
11

// Fig. 6.14: MethodOverloadTest.java


// Application to test class MethodOverload.
public class MethodOverloadTest
{
public static void main( String args[] )
{
MethodOverload methodOverload = new MethodOverload();
methodOverload.testOverloadedMethods();
} // end main
} // end class MethodOverloadTest

Outline

MethodOverloadTest
.java

Called square with int argument: 7


Square of integer 7 is 49
Called square with double argument: 7.500000
Square of double 7.5 is 56.250000

2005 Pearson
Education, Inc. All rights
reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

1
2
3
4
5
6

// Fig. 6.15: MethodOverloadError.java


// Overloaded methods with identical signatures
// cause compilation errors, even if return types are different.

Outline

public class MethodOverloadError


{

MethodOverload

7
8
9
10

// declaration of method square with int argument


public int square( int x )
{
return x * x;

11

12
13
14
15

// second declaration of method square with int argument


// causes compilation error even though return types are different
public double square( int y )

16
17
18

Error.java

ERROR:
Same method signature

{
return y * y;
}

19 } // end class MethodOverloadError

Compilation

error defined in
MethodOverloadError.java:15: square(int) is already
MethodOverloadError
public double square( int y )
^
1 error

2005 Pearson
Education, Inc. All rights
reserved.

Common Programming Error


Declaring overloaded methods with identical
parameter lists is a compilation error regardless
of whether the return types are different.

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Boolean Variables
The result of a boolean expression is either true
or false. These are the two values of data type
boolean.
We can declare a variable of data type boolean
and assign a boolean value to it.
boolean pass, done;
pass = 70 < x;
done = true;
if (pass) {

} else {

2005 Pearson Education, Inc. All rights reserved.

A method that returns a boolean value, such as

Boolean Methods
private boolean isValid(int value) {
if (value < MAX_ALLOWED)
return true;
} else {
return false;
}
}

Can be used as

if (isValid(30)) {

} else {

4th Ed Chapter 5 - 82
2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Comparing Objects

With primitive data types, we have only


one way to compare them, but with objects
(reference data type), we have two ways to
compare them.
1.

We can test whether two variables point to the


same object (use ==), or
2. We can test whether two distinct objects have the
same contents.

4th Ed Chapter 5 - 83
2005 Pearson Education, Inc. All rights reserved.

Using == With Objects (Sample 1)


String str1 = new String("Java");
String str2 = new String("Java");
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

They are not equal

Not equal because


str1 and str2 point to
different String
objects.

4th Ed Chapter 5 - 84

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Using == With Objects (Sample 2)


String str1 = new String("Java");
String str2 = str1;
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

It's equal here


because str1 and str2
point to the same
object.

They are equal

4th Ed Chapter 5 - 85

Using equals with String


String str1 = new String("Java");
String str2 = new String("Java");
if (str1.equals(str2)) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

They are equal

It's equal here


because str1 and str2
have the same
sequence of
characters.

4th Ed Chapter 5 - 86

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Semantics of ==

4th Ed Chapter 5 - 87

In Creating String Objects

4th Ed Chapter 5 - 88

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Initializing Objects with Constructors


Constructors
Initialize an object of a class
Java requires a constructor for every class
Java will provide a default no-argument constructor if
none is provided
Called when keyword new is followed by the class
name and parentheses

2005 Pearson Education, Inc. All rights reserved.

1
2

Outline
// GradeBook.java

// GradeBook class with a constructor to initialize the course name.

3
4

public class GradeBook

private String courseName; // course name for this GradeBook

7
8

// constructor initializes courseName with String supplied as argument

public GradeBook( String name )

10

{
courseName = name; // initializes courseName

11
12

} // end constructor

13
14

// method to set the course name

15

public void setCourseName( String name )

16

{
courseName = name; // store the course name

17
18

} // end method setCourseName

19
20

// method to retrieve the course name

21

public String getCourseName()

22

23
24

return courseName;

GradeBook.java
(1 of 2)

} // end method getCourseName

Constructor to initialize
courseName variable

This watermark does not appear in the registered version - http://www.clicktoconvert.com

25

Outline
// display a welcome message to the GradeBook user

26
27

public void displayMessage()

28

29

// this statement calls getCourseName to get the

30

// name of the course this GradeBook represents

31

System.out.printf( "Welcome to the grade book for\n%s!\n",

32

getCourseName() );

33

} // end method displayMessage

34
35 } // end class GradeBook

GradeBook.java
(2 of 2)

1
2
3

// GradeBookTest.java

Outline

// GradeBook constructor used to specify the course name at the


// time each GradeBook object is created.

4
5

public class GradeBookTest

// main method begins program execution

public static void main( String args[] )

10

// create GradeBook object

11

GradeBook gradeBook1 = new GradeBook(

12
13
14

"CS111 Introduction to Java Programming" );


GradeBook gradeBook2 = new GradeBook(
"CSC222 Computer Organization and Assembly Language" );

15
16

// display initial value of courseName for each GradeBook

17

System.out.printf( "gradeBook1 course name is: %s\n",

18
19
20
21

Call constructor to
create first grade
book object
Create second grade
book object

gradeBook1.getCourseName() );
System.out.printf( "gradeBook2 course name is: %s\n",
gradeBook2.getCourseName() );
} // end main

22
23 } // end class GradeBookTest
gradeBook1 course name is: CSC111 Introduction to Java Programming
gradeBook2 course name is: CSC222 Computer Organization and assembly Language

GradeBookTest.java

This watermark does not appear in the registered version - http://www.clicktoconvert.com

1
2
3
4
5
6
7
8
9

// Account.java
// Account class with a constructor to
// initialize instance variable balance.

Outline

public class Account


{
private double balance; // instance variable that stores the balance
// constructor

Account.java

double variable
balance

10
11
12
13
14
15
16
17
18
19
20
21

public Account( double initialBalance )


{
// validate that initialBalance is greater than 0.0;
// if it is not, balance is initialized to the default value 0.0
if ( initialBalance > 0.0 )
balance = initialBalance;
} // end Account constructor

22

} // end method credit

23
24

// return the account balance

25

public double getBalance()

26
27

// credit (add) an amount to the account


public void credit( double amount )
{
balance = balance + amount; // add amount to balance

return balance; // gives the value of balance to the calling method

28
} // end method getBalance
29
30 } // end class Account

Outline
1

// AccountTest.java

// Create and manipulate an Account object.

import java.util.Scanner;

4
5

public class AccountTest

// main method begins execution of Java application

public static void main( String args[] )

10

Account account1 = new Account( 50.00 ); // create Account object

11

Account account2 = new Account( -7.53 ); // create Account object

12
13

// display initial balance of each object

14

System.out.printf( "account1 balance: $%.2f\n",

15
16
17

account1.getBalance() );
System.out.printf( "account2 balance: $%.2f\n\n",
account2.getBalance() );

18

AccountTest.java
(1 of 3)

This watermark does not appear in the registered version - http://www.clicktoconvert.com

19
20
21

// create Scanner to obtain input from command window

Outline

Scanner input = new Scanner( System.in );


double depositAmount; // deposit amount read from user

22
23

System.out.print( "Enter deposit amount for account1: " ); // prompt

24

depositAmount = input.nextDouble(); // obtain user input

25

System.out.printf( "\nadding %.2f to account1 balance\n\n",

26
27

depositAmount );

Input a double value

account1.credit( depositAmount ); // add to account1 balance

28
29

// display balances

30

System.out.printf( "account1 balance: $%.2f\n",

31
32
33

account1.getBalance() );
System.out.printf( "account2 balance: $%.2f\n\n",

Input a double value

account2.getBalance() );

34
35

System.out.print( "Enter deposit amount for account2: " ); // prompt

36

depositAmount = input.nextDouble(); // obtain user input

37

System.out.printf( "\nadding %.2f to account2 balance\n\n",

38
39

depositAmount );
account2.credit( depositAmount ); // add to account2 balance

40

AccountTest.jav
a

AccountTest.java
(2 of 3)

41
42
43
44
45
46

// display balances
System.out.printf(
Outline

"account1 balance: $%.2f\n",

account1.getBalance() );
System.out.printf( "account2 balance: $%.2f\n",
account2.getBalance() );
} // end main

47

Output a double value

48 } // end class AccountTest


account1 balance: $50.00
account2 balance: $0.00

Lines 14 - 17

Enter deposit amount for account1: 25.53

Lines 23 - 25

adding 25.53 to account1 balance


account1 balance: $75.53
account2 balance: $0.00

Lines 30 - 33

Enter deposit amount for account2: 123.45


adding 123.45 to account2 balance
account1 balance: $75.53
account2 balance: $123.45

Lines 35 - 38

Lines 42 - 45

AccountTest.java
(3 of 3)

AccountTest.java

This watermark does not appear in the registered version - http://www.clicktoconvert.com

UML class diagram indicating that class Account has a


private balance attribute of UML type Double,
a constructor (with a parameter of UML type Double) and
two public operationscredit (with an amount
parameter of UML type Double) and getBalance (returns
UML type Double).

2005 Pearson Education, Inc. All rights reserved.

98

Example 4

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

1
2
3
4

// GradeBook6.java
// GradeBook class that solves class-average program using
// sentinel-controlled repetition.
import java.util.Scanner; // program uses class Scanner

5
6

public class GradeBook6

Outline

7 {
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

private String courseName; // name of course this GradeBook represents

GradeBook6.java
(1 of 3)

// constructor initializes courseName


public GradeBook( String name )
{
courseName = name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName( String name )

Assign a value to instance variable


courseName

Declare method setCourseName

courseName = name; // store the course name


} // end method setCourseName
// method to retrieve the course name
public String getCourseName()
{
return courseName;
} // end method getCourseName

Declare method getCourseName

2005 Pearson Education, Inc. All rights reserved.

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

// display a welcome message to the GradeBook user


public void displayMessage()
Declare method
{
displayMessage
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
getCourseName() );
} // end method displayMessage
GradeBook6.java

Outline

(2 of 3)
// determine the average of an arbitrary number of grades
public void determineClassAverage()
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int total; // sum of grades
Declare method
int gradeCounter; // number of grades entered
determineClassAverage
int grade; // grade value
double average; // number with decimal point for average
// initialization phase
total = 0; // initialize total
gradeCounter = 0; // initialize loop counter

Declare and initialize


Scanner variable input

Declare local int variables total,


gradeCounter and grade and
double variable average

// processing phase
// prompt for input and read grade from user
System.out.print( "Enter grade or -1 to quit: " );
grade = input.nextInt();

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

// loop until sentinel value read from user

56

Outline

while ( grade != -1 )

57

while loop iterates as long


as grade != the sentinel
value, -1

58
59

total = total + grade; // add grade to total

60

gradeCounter = gradeCounter + 1; // increment counter

61
62

// prompt for input and read next grade from user

63

System.out.print( "Enter grade or -1 to quit: " );

GradeBook6.java
(3 of 3)

grade = input.nextInt();

64

} // end while

65
66
67

// termination phase

68

// if user entered at least one grade...

69

if ( gradeCounter != 0 )

70

71

// calculate average of all grades entered

72

average = (double) total / gradeCounter;

73
74

// display total and average (with two digits of precision)

75

System.out.printf( "\nTotal of the %d grades entered is %d\n",


gradeCounter, total );

76

System.out.printf( "Class average is %.2f\n", average );

77
78

} // end if

79

else // no grades were entered, so output appropriate message

Calculate average
grade using
(double) to
perform explicit
conversion
Display average
grade

System.out.println( "No grades were entered" );

80

} // end method determineClassAverage

81
82

Display No grades were entered message

83 } // end class GradeBook

2005 Pearson Education, Inc. All rights reserved.

// Fig. 4.10: GradeBookTest.java

// Create GradeBook object and invoke its determineClassAverage method.

Outline

3
4

public class GradeBookTest6

public static void main( String args[] )

Create a new GradeBook6


object

// create GradeBook6 object myGradeBook and

// pass course name to constructor

10

GradeBook6 myGradeBook = new GradeBook6(


"CS101 Introduction to Java Programming" );

11
12
13
14
15

myGradeBook.displayMessage(); // display welcome

GradeBookTest6.java

Pass the courses name to the


GradeBook6 constructor as a
string
message

myGradeBook.determineClassAverage(); // find average of grades


} // end main

16
17 } // end class GradeBookTest
Welcome to the grade book for
CS101 Introduction to Java Programming!
Enter
Enter
Enter
Enter

grade
grade
grade
grade

or
or
or
or

-1
-1
-1
-1

to
to
to
to

quit:
quit:
quit:
quit:

Call determineClassAverage
method

97
88
72
-1

Total of the 3 grades entered is 257


Class average is 85.67

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

103

Example 5

2005 Pearson Education, Inc. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

// GradeBook.java
// GradeBook class uses switch statement to count A, B, C, D and F grades.
import java.util.Scanner; // program uses class Scanner
public class GradeBook
{
private String courseName; // name of course this GradeBook represents
private int total; // sum of grades
private int gradeCounter; // number of grades entered
private int aCount; // count of A grades
private int bCount; // count of B grades
private int cCount; // count of C grades
private int dCount; // count of D grades
private int fCount; // count of F grades
// constructor initializes courseName;
// int instance variables are initialized to 0 by default
public GradeBook( String name )
{
courseName = name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName( String name )
{
courseName = name; // store the course name
} // end method setCourseName

Outline

104

GradeBook.java
(1 of 5)
Lines 8-14

This watermark does not appear in the registered version - http://www.clicktoconvert.com

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

// method to retrieve the course name


public String getCourseName()
{
return courseName;
} // end method getCourseName
// display a welcome message to the GradeBook user
public void displayMessage()
{
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
getCourseName() );
} // end method displayMessage

Outline

105

GradeBook.java
(2 of 5)

Lines 50-54

// input arbitrary number of grades from user


public void inputGrades()
{
Scanner input = new Scanner( System.in );
int grade; // grade entered by user

Display prompt

System.out.printf( "%s\n%s\n
%s\n
%s\n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter" );

// loop until user enters the end-of-file indicator


106
while ( input.hasNext() )
{
grade = input.nextInt(); // read grade
Loop condition uses method hasNext to
total += grade; // add grade to total
++gradeCounter; // increment number of grades
determine whether there is more data to

Outline

// call method to increment appropriate counter


incrementLetterGradeCounter( grade );
} // end while
} // end method inputGrades

input

GradeBook.java
(3 of 5)
Line 57
Line 72
controlling
expression
Lines 72-94

// add 1 to appropriate counter for specified grade


public void incrementLetterGradeCounter( int numericGrade )
{

(grade / 10 ) is controlling
// determine which grade was entered
expression
switch ( grade / 10 )
{
case 9: // grade was between 90
switch statement determines
case 10: // and 100
which case label to execute,
++aCount; // increment aCount
depending on controlling
break; // necessary to exit switch

expression
case 8: // grade was between 80 and 89
++bCount; // increment bCount
break; // exit switch

This watermark does not appear in the registered version - http://www.clicktoconvert.com

83
84
85
86
87
88
89
90
91
92
93
94

case 7: // grade was between 70 and 79

Outline

++cCount; // increment cCount


break; // exit switch
case 6: // grade was between 60 and 69
++dCount; // increment dCount
break; // exit switch
default: // grade was less than 60
++fCount; // increment fCount
break; // optional; will exit switch anyway
} // end switch

95

} // end method incrementLetterGradeCounter

96
97

// display a report based on the grades entered by user

98
99
100

public void displayGradeReport()


{
System.out.println( "\nGrade Report:" );

101
102
103
104
105
106
107

GradeBook.java
(4 of 5)

Line 91 default
case

default case for grade less than 60

// if user entered at least one grade...


if ( gradeCounter != 0 )
{
// calculate average of all grades entered
double average = (double) total / gradeCounter;

108

// output summary of results

109

System.out.printf( "Total of the %d grades entered is %d\n",

110

Outline

gradeCounter, total );

111

System.out.printf( "Class average is %.2f\n", average );

112

System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n",

113

"Number of students who received each grade:",

114

"A: ", aCount,

// display number of A grades

115

"B: ", bCount,

// display number of B grades

116

"C: ", cCount,

// display number of C grades

117

"D: ", dCount,

// display number of D grades

118

"F: ", fCount ); // display number of F grades

119

} // end if

120

else // no grades were entered, so output appropriate message

121
122

107

System.out.println( "No grades were entered" );


} // end method displayGradeReport

123 } // end class GradeBook

GradeBook.java
(5 of 5)

108

This watermark does not appear in the registered version - http://www.clicktoconvert.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// GradeBookTest.java
// Create GradeBook object, input grades and display grade report.
public class GradeBookTest
{
public static void main( String args[] )
{
// create GradeBook object myGradeBook and
// pass course name to constructor
GradeBook myGradeBook = new GradeBook(
"CSC111 Introduction to Java Programming" );

Outline

109

Call GradeBook public


methods to count grades

myGradeBook.displayMessage(); // display welcome message


myGradeBook.inputGrades(); // read grades from user
myGradeBook.displayGradeReport(); // display report based on grades
} // end main
} // end class GradeBookTest

GradeBookTest.
java
(1 of 2)

Lines 13-15

Welcome to the grade book for


CSC111 Introduction to Java Programming!
Enter the integer grades in the range 0-100.
Type the end-of-file indicator to terminate input:
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
99
92
45
57
63
71
76
85
90
100
^Z
Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80
Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2

Outline

110

GradeBookTest.
java
(2 of 2)

Program output

This watermark does not appear in the registered version - http://www.clicktoconvert.com

111

Example 6
Implement the following integer methods:
a) Method celsius returns the Celsius equivalent of a Fahrenheit temperature, using
the calculation
C = 5.0 / 9.0 * ( F - 32 );
b) Method fahrenheit returns the Fahrenheit equivalent of a Celsius temperature,
using the calculation
F = 9.0 / 5.0 * C + 32;
c) Use the methods from parts (a) and (b) to write an application that enables the
user either to enter a Fahrenheit temperature and display the Celsius equivalent
or to enter a Celsius temperature and display the Fahrenheit equivalent.

2005 Pearson Education, Inc. All rights reserved.

112

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

113

114

This watermark does not appear in the registered version - http://www.clicktoconvert.com

// Time1.java

// Time1 class declaration maintains the time in 24-hour format.

3
4

public class Time1

Outline

115

private instance variables

private int hour;

private int minute; // 0 - 59

// 0 23

private int second; // 0 - 59

No Constructor

9
10

// set a new time value using universal time; ensure that

11

// the data remains consistent by setting invalid values to zero

12

public void setTime( int h, int m, int s )

Time1.jav
a
(1 of 2)

Declare public method setTime

13
14

hour = ( ( h >= 0 && h < 24 ) ? h : 0 );

15

minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute

16
17

// validate hour

second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second


} // end method setTime

18

Validate parameter values before


setting instance variables

19

// convert to String in universal-time format (HH:MM:SS)

20

public String toUniversalString()

21

Time1.jav
format strings
a

} // end method toUniversalString

24
25

// convert to String in standard-time format (H:MM:SS AM or PM)

26

public String toString()

27

28
29
30
31

116

return String.format( "%02d:%02d:%02d", hour, minute, second );

22
23

Outline

(2 of 2)

return String.format( "%d:%02d:%02d %s",


( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
minute, second, ( hour < 12 ? "AM" : "PM" ) );
} // end method toString

32 } // end class Time1

( hour == 0 || hour == 12 ) is true


If ( hour < 12 ) is true

( hour == 0 || hour == 12 ) is false

This watermark does not appear in the registered version - http://www.clicktoconvert.com

117

Time Class Case Study (Cont.)


String method format
Similar to printf except it returns a formatted
string instead of displaying it in a command window

new keyword implicitly invokes Time1s


default constructor since Time1 does not
declare any constructors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// Time1Test.java
// Time1 object used in an application.
public class Time1Test
{
public static void main( String args[] )
{

Outline

Create a Time1
object

// create and initialize a Time1 object


Time1 time = new Time1(); // invokes Time1 constructor

// output string representations of the time


System.out.print( "The initial universal time is: " );
System.out.println( time.toUniversalString() );
System.out.print( "The initial standard time is: " );
System.out.println( time.toString() );
System.out.println(); // output a blank line

Time1Test.java
(1 of 2)

Call toUniversalString
method
Call toString method

return string

118

This watermark does not appear in the registered version - http://www.clicktoconvert.com

18
19
20
21

// change time and output updated time


Call setTime
time.setTime( 13, 27, 6 );
method
System.out.print( "Universal time after setTime is: " );
System.out.println( time.toUniversalString() );

22
System.out.print( "Standard time after setTime is: " );
23
System.out.println( time.toString() );
24
System.out.println(); // output a blank line
25
26
// set time with invalid values; output updated time
27
time.setTime( 99, 99, 99 );
28
System.out.println( "After attempting invalid settings:" );
29
System.out.print( "Universal time: " );
30
System.out.println( time.toUniversalString() );
31
System.out.print( "Standard time: " );
32
System.out.println( time.toString() );
33
} // end main
34 } // end class Time1Test

Outline

119

Time1Test.java
Call setTime(2 of 2)
method with
invalid values

The initial universal time is: 00:00:00


The initial standard time is: 12:00:00 AM
Universal time after setTime is: 13:27:06
Standard time after setTime is: 1:27:06 PM
After attempting invalid settings:
Universal time: 00:00:00
Standard time: 12:00:00 AM

120

Controlling Access to Members

Remember:
public methods a view of the services the class
provides to the classs clients
private variables and private methods are not
accessible to the classs clients

This watermark does not appear in the registered version - http://www.clicktoconvert.com

//

// Private members of class Time1 are not accessible.

MemberAccessTest.java

public class MemberAccessTest

public static void main( String args[] )

Time1 time = new Time1(); // create and initialize Time1 object

8
9

time.hour = 7;

10

time.minute = 15; // error: minute has private access in Time1

11
12

// error: hour has private access in Time1

time.second = 30; // error: second has private access in Time1


} // end main

13 } // end class MemberAccessTest

Outline

121

MemberA
ccessTest
.java

Attempting to access private instance


variables

MemberAccessTest.java:9: hour has private access in Time1


time.hour = 7;
// error: hour has private access in Time1
^
MemberAccessTest.java:10: minute has private access in Time1
time.minute = 15; // error: minute has private access in Time1
^
MemberAccessTest.java:11: second has private access in Time1
time.second = 30; // error: second has private access in Time1
^
3 errors

Displaying Text in a Dialog Box


Windows and dialog boxes
Many Java applications use these to display output
JOptionPane provides prepackaged dialog boxes
called message dialogs

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Displaying Text in a Dialog Box


Package javax.swing
Contains classes to help create graphical user
interfaces (GUIs)
Contains class JOptionPane
Declares static method showMessageDialog for
displaying a message dialog

// Dialog1.java

Outline

// Printing multiple lines in dialog box.


import javax.swing.JOptionPane; // import class JOptionPane

4
5

public class Dialog1

public static void main( String args[] )

9
10
11

// display a dialog with the message


JOptionPane.showMessageDialog( null, "Welcome\nto\nJava" );
} // end main

Import class
JOptionPane

12 } // end class Dialog1

Dialog1.java
Do not explicitly creating an
object because it is
declared as static method

Show a message
dialog with text

When the first argument is


null, the dialog box
appears in the center of
the computer screen

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Entering Text in a Dialog Box


Input dialog
Allows user to input information
Created using method showInputDialog from
class JOptionPane

1
2
3

//

NameDialog.java

Outline

// Basic input with a dialog box.


import javax.swing.JOptionPane;

4
5

public class NameDialog

public static void main( String args[] )

// prompt user to enter name

10

String name =

11

Show input dialog

JOptionPane.showInputDialog( "What is your name?" );

12
13

// create the message

14

String message =

15

String.format( "Welcome, %s, to Java Programming!", name );

16
17
18
19

// display the message to welcome the user by name


JOptionPane.showMessageDialog( null, message );
} // end main

20 } // end class NameDialog

NameDialog.java

Format a String to
output to user

This watermark does not appear in the registered version - http://www.clicktoconvert.com

127

Example 7

Write a program that computes the area of a circular region (the shaded area
in the diagram) given the radii of the inner and the outer circles, ri and ro,
respectively.

We compute the area of the circular region by subtracting the area of the
inner circle from the area of the outer circle. Define a Circle class that has
methods to compute the area and the circumference. You set the circles
radius with the setRadius method or via a constructor.

128

This watermark does not appear in the registered version - http://www.clicktoconvert.com

129

130

This watermark does not appear in the registered version - http://www.clicktoconvert.com

131

Input Dialog box


JoptionPane is a class in the
package Javax.swing
To convert numeric string into Double

132

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Q:
Modify the Bicycle class so instead of assigning the
name of an owner (Student), you can assign the owner
object itself. Model this new Bicycle class

The Definition of the Bicycle Class


class Bicycle {
// Data Member
private String ownerName;
//Constructor: Initialzes the data member
public void Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

class BicycleRegistration {
public static void main(String[]

args) {

Bicycle bike1, bike2;


String

owner1, owner2;

bike1 = new Bicycle( ) ;

//Create and assign values to bike1

bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ) ;

//Create and assign values to bike2

bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( ) ; //Output the information
owner2 = bike2.getOwnerName( ) ;

}
}

System.out.println(owner1

+ " owns a bicycle.");

System.out.println(owner2

+ " also owns a bicycle.");

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Modified class

Extend the LibraryCard class by adding the expiration date as a


new property of a library card. Define the following four
methods:
//sets the expiration date
public void setExpDate(GregorianCalendar date) {...}
//returns the expiration year
public int getExpYear( ) { ... }
//returns the expiration month
public int getExpMonth( ) { ... }
//returns the expiration day
public int getExpDay( ) { ... }

This watermark does not appear in the registered version - http://www.clicktoconvert.com

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Reserved Word this


The reserved word this is called a self-referencing pointer
because it refers to an object from the object's method.
: Object
this

The reserved word this can be used in three different ways.


We will see all three uses in this chapter.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

The Use of this in the add Method


public Fraction add(Fraction frac) {
int
a, b, c, d;
Fraction sum;
a = this.getNumerator();
//get the receiving
b = this.getDenominator(); //object's num and
denom
c = frac.getNumerator();
//get frac's num
d = frac.getDenominator(); //and denom
sum = new Fraction(a*d + b*c, b*d);
return sum;
}

Using this to Refer to Data


Members
In the previous example, we showed the use of this
to call a method of a receiving object.
It can be used to refer to a data member as well.
class Person {
int

age;

public void setAge(int val)


{
this.age = val;
}
. . .
}

This watermark does not appear in the registered version - http://www.clicktoconvert.com

145

Referring to the Current Objects


Members with the this Reference
The this reference
Any object can access a reference to itself with
keyword this
Non-static methods implicitly use this when
referring to the objects instance variables and other
methods
Can be used to access instance variables when they
are shadowed by local variables or method parameters

A .java file can contain more than one


class
But only one class in each .java file can be public

// ThisTest.java

2
3

// this used implicitly and explicitly to refer to members of an object.

4
5

public class ThisTest


{

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Outline

Create new SimpleTime


object

public static void main( String args[] )


{
SimpleTime time = new SimpleTime( 15, 30, 19 );

146

ThisTest.java

System.out.println( time.buildString() );

(1 of 2)

} // end main
} // end class ThisTest

One class is public


// class SimpleTime demonstrates the "this" reference
class SimpleTime
{
private int hour;
// 0-23
private int minute; // 0-59
private int second; // 0-59

Declare instance
variables

// if the constructor uses parameter names identical to


// instance variable names the "this" reference is
// required to distinguish between names
public SimpleTime( int hour, int minute, int second )
{
this.hour = hour;
// set "this" object's hour
this.minute = minute; // set "this" object's minute
this.second = second; // set "this" object's second
} // end SimpleTime constructor

Using this to access the objects instance


variables

Method parameters
shadow instance
variables
Constructor

This watermark does not appear in the registered version - http://www.clicktoconvert.com

30

// use explicit and implicit "this" to call toUniversalString

31

public String buildString()

32

{
return String.format( "%24s: %s\n%24s: %s",

33

"this.toUniversalString()", this.toUniversalString(),

34

"toUniversalString()", toUniversalString() );

35
36

} // end method buildString

37
38

// convert to String in universal-time format (HH:MM:SS)

39

public String toUniversalString()

40

Using this explicitly and


implicitly to call
toUniversalString

41

// "this" is not required here to access instance variables,

42

// because method does not have local variables with same

43

// names as instance variables

44

return String.format( "%02d:%02d:%02d",

45
46

147

this.hour, this.minute, this.second );


} // end method toUniversalString

47 } // end class SimpleTime


this.toUniversalString(): 15:30:19
toUniversalString(): 15:30:19

Use of this not


necessary here

148

Common Programming Error


It is often a logic error when a method contains a
parameter or local variable that has the same name
as a field of the class.
In this case, use reference this if you wish to access
the field of the classotherwise, the method
parameter or local variable will be referenced.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

149

Error-Prevention Tip
Avoid method parameter names or local variable
names that conflict with field names. This helps
prevent subtle, hard-to-locate bugs.

Overloaded Constructor
The same rules apply for overloaded constructors
this is how we can define more than one constructor to a class

public Person( ) { ... }


public Person(int age) { ... }

Rule 1

public Pet(int age) { ... }


public Pet(String name) { ... }

Rule 2

This watermark does not appear in the registered version - http://www.clicktoconvert.com

151

Overloaded constructors
Provide multiple constructor definitions with different
signatures

No-argument constructor
A constructor invoked without arguments

The this reference can be used to invoke


another constructor
Allowed only as the first statement in a constructors body

// Time2.java

2
3

// Time2 class declaration with overloaded constructors.

4
5

public class Time2


{

6
7
8

private int hour;


// 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59

152

Time2.jav
a

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Outline

// Time2 no-argument constructor: initializes each instance variable


// to zero; ensures that Time2 objects start in a consistent state
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor

No-argument
constructor

// Time2 constructor: hour supplied, minute and second defaulted to 0


public Time2( int h )
{
this( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor

Invoke threeargument
constructor

// Time2 constructor: hour and minute supplied, second defaulted to 0


public Time2( int h, int m )
{
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor

(1 of 4)

This watermark does not appear in the registered version - http://www.clicktoconvert.com

29

// Time2 constructor: hour, minute and second supplied

30

public Time2( int h, int m, int s )

31

Outline

153

39

Call setTime
method
} // end Time2 three-argument constructor
Time2.jav
Constructor takes a
// Time2 constructor: another Time2 object supplied
a
reference to another
public Time2( Time2 time )
{
Time2 object as a
// invoke Time2 three-argument constructor
(2 of 4)
parameter
this( time.getHour(), time.getMinute(), time.getSecond() );

40

} // end Time2 constructor with a Time2 object argument

41

Could have directly


accessed instance
// set a new time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
variables of object
public void setTime( int h, int m, int s )
time here

32
33
34
35
36
37
38

42
43
44
45
46

setTime( h, m, s ); // invoke setTime to validate time

// Set Methods

47

setHour( h );

48

setMinute( m ); // set the minute

49

setSecond( s ); // set the second

50

// set the hour

} // end method setTime

51

52

// validate and set hour

53

public void setHour( int h )

54

{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );

55
56

} // end method setHour

57
58

// validate and set minute

59

public void setMinute( int m )

60

{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );

61
62

} // end method setMinute

63
64

// validate and set second

65

public void setSecond( int s )

66

{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );

67
68

} // end method setSecond

69
70

// Get Methods

71

// get hour value

72

public int getHour()

73

74
75
76

return hour;
} // end method getHour

This should be the


first statement in
the constructor.

154

This watermark does not appear in the registered version - http://www.clicktoconvert.com

77
78
79

// get minute value


public int getMinute()
{

80
81
82
83
84
85
86
87
88
89
90

return minute;
} // end method getMinute

155

// get second value


public int getSecond()
{
return second;
} // end method getSecond
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()

91
{
92
return String.format(
93
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
94
} // end method toUniversalString
95
96
// convert to String in standard-time format (H:MM:SS AM or PM)
97
public String toString()
98
{
99
return String.format( "%d:%02d:%02d %s",
100
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
101
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
102
} // end method toString
103 } // end class Time2

156

Common Programming Error


It is a syntax error when this is used in a
constructors body to call another constructor of
the same class if that call is not the first
statement in the constructor. It is also a syntax
error when a method attempts to invoke a
constructor directly via this .

This watermark does not appear in the registered version - http://www.clicktoconvert.com

157

Common Programming Error


A constructor can call methods of the class. Be
aware that the instance variables might not yet
be in a consistent state, because the constructor
is in the process of initializing the object. Using
instance variables before they have been
initialized properly is a logic error.

158

Software Engineering Observation


When one object of a class has a reference to
another object of the same class, the first object
can access all the second objects data and
methods (including those that are private ).

This watermark does not appear in the registered version - http://www.clicktoconvert.com

159

Time Class Case Study: Overloaded


Constructors (Cont.)
Using set methods
Having constructors use set methods to modify
instance variables instead of modifying them directly
simplifies implementation changing

// Fig. 8.6: Time2Test.java

// Overloaded constructors used to initialize Time2 objects.

Outline

160

3
4

public class Time2Test

public static void main( String args[] )

Call overloaded
constructorsTime2Test

Time2 t1 = new Time2();

// 00:00:00

Time2 t2 = new Time2( 2 );

// 02:00:00

10

Time2 t3 = new Time2( 21, 34 );

// 21:34:00

11

Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42

12

Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00

13

Time2 t6 = new Time2( t4 );

// 12:25:42

14
15

System.out.println( "Constructed with:" );

16

System.out.println( "t1: all arguments defaulted" );

17

System.out.printf( "

%s\n", t1.toUniversalString() );

18

System.out.printf( "

%s\n", t1.toString() );

19

.java

(1 of 3)

This watermark does not appear in the registered version - http://www.clicktoconvert.com

20
21

System.out.println(
"t2: hour specified; minute and second defaulted" );

22

System.out.printf( "

%s\n", t2.toUniversalString() );

23

System.out.printf( "

%s\n", t2.toString() );

24
25
26

System.out.println(
"t3: hour and minute specified; second defaulted" );

27

System.out.printf( "

%s\n", t3.toUniversalString() );

28

System.out.printf( "

%s\n", t3.toString() );

Outline

161

Time2Test
.java
(2 of 3)

29
30

System.out.println( "t4: hour, minute and second specified" );

31

System.out.printf( "

%s\n", t4.toUniversalString() );

32

System.out.printf( "

%s\n", t4.toString() );

33
34

System.out.println( "t5: all invalid values specified" );

35

System.out.printf( "

%s\n", t5.toUniversalString() );

36

System.out.printf( "

%s\n", t5.toString() );

37

38

System.out.println( "t6: Time2 object t4 specified" );

39

System.out.printf( "

%s\n", t6.toUniversalString() );

System.out.printf( "

%s\n", t6.toString() );

40
41

} // end main

Outline
Time2Test.java

42 } // end class Time2Test


t1: all arguments defaulted
00:00:00
12:00:00 AM
t2: hour specified; minute and second defaulted
02:00:00
2:00:00 AM
t3: hour and minute specified; second defaulted
21:34:00
9:34:00 PM
t4: hour, minute and second specified
12:25:42
12:25:42 PM
t5: all invalid values specified
00:00:00
12:00:00 AM
t6: Time2 object t4 specified
12:25:42
12:25:42 PM

(3 of 3)

162

This watermark does not appear in the registered version - http://www.clicktoconvert.com

163

Default and No-Argument Constructors


Every class must have at least one
constructor
If no constructors are declared, the compiler will
create a default constructor
Takes no arguments and initializes instance variables to
their initial values specified in their declaration or to
their default values
Default values are zero for primitive numeric
types, false for boolean values and null for
references

If constructors are declared, the default initialization


for objects of the class will be performed by a noargument constructor (if one is declared)

164

Common Programming Error


5If a class has constructors, you should conclude a
no-argument constructor to initialize an object of the
class. In case you did not conclude a no-argument
constructor a compilation error occurs.
A constructor can be called with no arguments only
if the class does not have any constructors or if the
class has a public no-argument constructor.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Review

Declaration vs. Creation


1

Customer

customer;

customer

new

customer
1

: Customer

Customer( );

1. The identifier customer is


declared and space is
allocated in memory.

2. A Customer object is
created and the identifier
customer is set to refer to
it.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

State-of-Memory vs. Program


Object Name

Class Name

customer
customer : Customer

: Customer

Program Diagram
Notation

State-of-Memory
Notation

Name vs. Objects


Customer

customer;

customer

new

Customer( );

customer

new

Customer( );

customer

Created with
the first new.

: Customer

: Customer

Created with the second


new. Reference to the first
Customer object is lost.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

This watermark does not appear in the registered version - http://www.clicktoconvert.com

This watermark does not appear in the registered version - http://www.clicktoconvert.com

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Sending a Message
Method Name
The name of the
message we are
sending.

Object Name
Name of the object to
which we are sending a
message.

myWindow

setVisible

Argument
The argument we are
passing with the
message.

true

) ;

account.deposit( 200.0 );
student.setName(john);
car1.startEngine( );

More
Examples

Execution Flow
Program Code

State-of-Memory Diagram

myWindow
JFrame
Jframe

myWindow;

myWindow

= new JFrame( );

: JFrame

myWindow.setSize(300, 200);

width

300

myWindow.setTitle
(My
(My First
First Java
Java Program);
Program);

height

200

myWindow.setVisible(true);

title
visible

The diagram shows only four of the many


data members of a JFrame object.

My
First
true
Java

This watermark does not appear in the registered version - http://www.clicktoconvert.com

Ali AlKebir has the course CSC111 3


Fahd Hassan has the course CSC222 3

2005 Pearson Education, Inc. All rights reserved.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

179

static Class Members


static fields
Also known as class variables
Represents class-wide information
Used when:
all objects of the class should share the same copy of this
instance variable or
this instance variable should be accessible even when no
objects of the class exist

Can be accessed with the class name or an object name


and a dot (.)
Must be initialized in their declarations, or else the
compiler will initialize it with a default value (0 for ints)

180

Software Engineering Observation


Use a static variable when all objects of a
class must use the same copy of the variable.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

181

Software Engineering Observation


Static class variables and methods exist, and
can be used, even if no objects of that class have
been instantiated.

// Fig. 8.12: Employee.java

// Static variable used to maintain a count of the number of

// Employee objects in memory.

182

4
5

public class Employee

Declare a
static field

private String firstName;

private String lastName;

private static int count = 0; // number of objects in memory

10
11

// initialize employee, add 1 to static count and

12

// output String indicating that constructor was called

13

public Employee( String first, String last )

14

15

firstName = first;

16

lastName = last;

Increment
static field

17
18

count++;

19

System.out.printf( "Employee constructor: %s %s; count = %d\n",

20
21
22

// increment static count of employees

firstName, lastName, count );


} // end Employee constructor

This watermark does not appear in the registered version - http://www.clicktoconvert.com

23
24
25
26
27
28
29

// subtract 1 from static count when garbage


// collector calls finalize to clean up object;
// confirm that finalize was called
protected void finalize()
{
count--; // decrement static count of employees
System.out.printf( "Employee finalizer: %s %s; count = %d\n",

30
31

firstName, lastName, count );


} // end method finalize

32
33
34

// get first name


public String getFirstName()

183

Declare method
finalize

35
36

37
38
39

} // end method getFirstName


// get last name

40
41

public String getLastName()


{

42
43
44

return lastName;
} // end method getLastName

return firstName;

Implicit call finalize when destruction of the object

45
// static method to get static count value
46
public static int getCount()
47
{
48
return count;
49
} // end method getCount
50 } // end class Employee

Declare static method


getCount to get
static field count

184

// Fig. 8.13: EmployeeTest.java

// Static member demonstration.

3
4

public class EmployeeTest

public static void main( String args[] )

// show that count is 0 before creating Employees

System.out.printf( "Employees before instantiation: %d\n",

10
11

Employee.getCount() );

Call static method getCount using class name Employee

12

// create two Employees; count should be 2

13

Employee e1 = new Employee( "Susan", "Baker" );

14

Employee e2 = new Employee( "Bob", "Blue" );

15

Create new
Employee
objects

This watermark does not appear in the registered version - http://www.clicktoconvert.com

185

16

// show that count is 2 after creating two Employees

17

System.out.println( "\nEmployees after instantiation: " );

18

System.out.printf( "via e1.getCount(): %d\n", e1.getCount() );

19

System.out.printf( "via e2.getCount(): %d\n", e2.getCount() );

20

System.out.printf( "via Employee.getCount(): %d\n",


Employee.getCount() );

21
22
23

// get names of Employees

24

System.out.printf( "\nEmployee 1: %s %s\nEmployee 2: %s %s\n\n",

25

e1.getFirstName(), e1.getLastName(),

26
35

e2.getFirstName(), e2.getLastName() );

Call static method


getCount inside
objects

Call static
method
getCount
outside objects

186
36

// show Employee count after calling garbage collector; count

37

// displayed may be 0, 1 or 2 based on whether garbage collector

38

// executes immediately and number of Employee objects collected

39

System.out.printf( "\nEmployees %d\n",

40
41

Employee.getCount() );
} // end main

42 } // end class EmployeeTest

Call static method


getCount

Employees before instantiation: 0


Employee constructor: Susan Baker; count = 1
Employee constructor: Bob Blue; count = 2
Employees after instantiation:
via e1.getCount(): 2
via e2.getCount(): 2
via Employee.getCount(): 2
Employee 1: Susan Baker
Employee 2: Bob Blue

This watermark does not appear in the registered version - http://www.clicktoconvert.com

187

static Class Members


String objects are immutable
String concatenation operations actually result in the
creation of a new String object
static methods cannot access non-static class members
Also cannot use the this reference

188

Common Programming Error


A compilation error occurs if a static method
calls an instance (non-static) method in the same
class by using only the method name.
Similarly, a compilation error occurs if a static
method attempts to access an instance variable
in the same class by using only the variable
name.

This watermark does not appear in the registered version - http://www.clicktoconvert.com

189

Common Programming Error


Referring to this in a static method is a
syntax error.

Vous aimerez peut-être aussi