Chapter 8 – Object-Based Programming

Download Report

Transcript Chapter 8 – Object-Based Programming

Chapter 8 – Object-Based Programming
Outline
8.1
8.2
8.3
8.4
8.5
8.6
8.7
8.8
8.9
8.10
8.11
8.12
8.13
8.14
8.15
Introduction
Implementing a Time Abstract Data Type with a Class
Class Scope
Controlling Access to Members
Creating Packages
Initializing Class Objects: Constructors
Using Overloaded Constructors
Using Set and Get Methods
8.8.1
Executing an Applet that Uses Programmer-Defined
Packages
Software Reusability
Final Instance Variables
Composition: Objects as Instance Variables of Other Classes
Package Access
Using the this Reference
Finalizers
Static Class Members
 2002 Prentice Hall. All rights reserved.
Chapter 8 – Object-Based Programming
Outline
8.16
Data Abstraction and Encapsulation
8.16.1 Example: Queue Abstract Data Type
8.17
(Optional Case Study) Thinking About Objects: Starting to
Program the Classes for the Elevator Simulation
 2002 Prentice Hall. All rights reserved.
8.1
Introduction
• Object Oriented Programming (OOP)
– Encapsulates data (attributes) and methods (behaviors)
• Objects
– Allows objects to communicate
• Well-defined interfaces
 2002 Prentice Hall. All rights reserved.
8.1
Introduction (cont.)
• Procedural programming language
– C is an example
– Action-oriented
– Functions are units of programming
• Object-oriented programming language
– Java is an example
– Object-oriented
– Classes are units of programming
• Functions, or methods, are encapsulated in classes
 2002 Prentice Hall. All rights reserved.
8.1
Introduction (cont.)
• This section discusses
– How to create objects
– How to use objects
 2002 Prentice Hall. All rights reserved.
8.2
Implementing a Time Abstract Data
Type with a Class
• We introduce classes Time1 and TimeTest
–
–
–
–
Time1.java defines class Time1
TimeTest.java defines class TimeTest
public classes must be defined in separate files
Class Time1 will not execute by itself
• Does not have method main
• Does not extend JApplet
• TimeTest, which has method main, creates (instantiates)
and uses Time1 object
 2002 Prentice Hall. 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
29
30
31
32
33
// Fig. 8.1: Time1.java
// Time1 class definition maintains the time in 24-hour format.
// Java core packages
import java.text.DecimalFormat;
public class Time1 extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
Outline
Time1 (subclass) inherits Time1.java
superclass java.lang.Object
(Chapter 9 discusses inheritance)Line 7
Time1 (subclass)
private variables (and methods)inherits
are superclass
java.lang.Object
accessible only to methods in this class
// Time1 constructor initializes each instance variable
// to zero. Ensures that each Time1 object starts in a
// consistent state.
Lines 8-10
public methods (and variables)
public Time1()
private variables
are accessible wherever program
{
has Time1 reference
setTime( 0, 0, 0 );
}
Lines 15, 22 and 30
public methods
Time1
constructor creates
// Set a new time value using universal time.
Perform
Time1
object
then invokes
// validity checks on the data. Set invalid
values
to zero.
public void setTime( int h, int m, int s )
Lines 15-18
method setTime
{
Time1 constructor
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
invokes method
minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); Method setTime sets then
private
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
variables according tosetTime
arguments
}
// convert to String in universal-time format
public String toUniversalString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
Lines 22-27
Method setTime sets
private variables
according to arguments
 2002 Prentice Hall.
All rights reserved.
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
return twoDigits.format( hour ) + ":" +
twoDigits.format( minute ) + ":" +
Method
twoDigits.format( second );
toString is a method
from java.lang.Object
}
// convert to String in standard-time format
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) +
":" + twoDigits.format( minute ) +
":" + twoDigits.format( second ) +
( hour < 12 ? " AM" : " PM" );
}
}
// end class Time1
Outline
Time1.java
Line 40
Method toString is
a method from
java.lang.Object
Line 40
Time1 overrides this
Time1 overrides this method to
provide more appropriate method method to provide more
appropriate method
 2002 Prentice Hall.
All rights reserved.
8.2
Implementing a Time Abstract Data
Type with a Class (cont.)
• Every Java class must extend another class
– Time1 extends java.lang.Object
– If class does not explicitly extend another class
• class implicitly extends Object
• Class constructor
–
–
–
–
–
–
Same name as class
Initializes instance variables of a class object
Called when program instantiates an object of that class
Can take arguments, but cannot return data types
Class can have several constructors, through overloading
Class Time1 (lines 15-18)
 2002 Prentice Hall. All rights reserved.
8.2
Implementing a Time Abstract Data
Type with a Class (cont.)
• Overriding methods
– Method Object.toString
• Gives String representation of object
• We want String in standard-time format
– Time1 overrides method toString (lines 40-48)
• Overriding method gives String in standard-time format
• If we remove lines 40-48
– Time1 still compiles correctly
– Uses method java.lang.Object.toString
– But gives String representation of object
 2002 Prentice Hall. 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
29
30
31
32
33
34
35
// Fig. 8.2: TimeTest1.java
// Class TimeTest1 to exercise class Time1
// Java extension packages
import javax.swing.JOptionPane;
Outline
Declare and initialize instance of class
Time1 by calling Time1 constructor TimeTest1.java
public class TimeTest1 {
Line 12
Declare and initialize
// create Time1 object and manipulate it
public static void main( String args[] )
instance of class
TimeTest
interacts
with
Time1
{
Time1 by calling
Time1 time = new Time1(); // calls
Time1Time1
constructor
by calling
public methods Time1 constructor
// append String version of time to String output
String output = "The initial universal time is: " +
time.toUniversalString() +
"\nThe initial standard time is: " + time.toString() +
"\nImplicit toString() call: " + time;
// change time and append String version of time to output
time.setTime( 13, 27, 6 );
output += "\n\nUniversal time after setTime is: " +
time.toUniversalString() +
"\nStandard time after setTime is: " + time.toString();
Lines 16-31
TimeTest interacts
with Time1 by calling
Time1 public
methods
// use invalid values to change time and append String
// version of time to output
time.setTime( 99, 99, 99 );
output += "\n\nAfter attempting invalid settings: " +
"\nUniversal time: " + time.toUniversalString() +
"\nStandard time: " + time.toString();
JOptionPane.showMessageDialog( null, output,
"Testing Class Time1",
JOptionPane.INFORMATION_MESSAGE );
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
System.exit( 0 );
Outline
}
}
// end class TimeTest1
TimeTest1.java
 2002 Prentice Hall.
All rights reserved.
8.3
Class Scope
• Class scope
– Class instance variables and methods
– Members are accessible to all class methods
– Members can be referenced by name
• Block scope
– Variables defined in methods
• Known only to that method
 2002 Prentice Hall. All rights reserved.
8.4
Controlling Access to Members
• Member access modifiers
– Control access to class’ instance variables and methods
– public
• Variables and methods not accessible to class clients
– private
• Variables and methods not accessible to class clients
• Accessor method (“get” method)
– Allow clients to read private data
• Mutator method (“set” method)
– Allow clients to modify private data
 2002 Prentice Hall. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 8.3: TimeTest2.java
// Demonstrate errors resulting from attempts
// to access private members of class Time1.
public class TimeTest2 {
Outline
TimeTest2.java
public static void main( String args[] )
{
Time1 time = new Time1();
time.hour = 7;
}
}
Line 10
Compiler error –
TimeTest2 cannot
directly access
Compiler error – TimeTest2 cannotTime1’s private
directly access Time1’s private data
data
TimeTest2.java:10: hour has private access in Time1
time.hour = 7;
^
1 error
Fig. 8.3 Erroneous
attempt to access
private members of
class Time1.
 2002 Prentice Hall.
All rights reserved.
8.5
Creating Packages
• We can import packages into programs
–
–
–
–
Group of related classes and interfaces
Help manage complexity of application components
Facilitate software reuse
Provide convention for unique class names
• Popular package-naming convention
– Reverse Internet domain name
• e.g., com.deitel
 2002 Prentice Hall. 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
29
30
31
32
33
34
// Fig. 8.4: Time1.java
// Time1 class definition in a package
package com.deitel.jhtp4.ch08;
Class Time1 is placed
in this package
Time1.java
// Java core packages
import java.text.DecimalFormat;
public class Time1 extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
Outline
Class Time1 is in directory
com/deitel/jhtp4/ch08
// Time1 constructor initializes each instance variable
// to zero. Ensures that each Time1 object starts in a
// consistent state.
import class DecimalFormat
public Time1()
{
from package java.text
setTime( 0, 0, 0 );
}
Line 3
Class Time1 is placed
in this package
Line 3
Class Time1 is in
directory
com/deitel/jhtp4
/ch08
Line 6
import class
DecimalFormat
from package
java.text
from
package java.text
Line 33
DecimalFormat
from package
java.text
"00" );
// Set a new time value using universal time. Perform
// validity checks on the data. Set invalid values to zero.
public void setTime( int h, int m, int s )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
DecimalFormat
}
// convert to String in universal-time format
public String toUniversalString()
{
DecimalFormat twoDigits = new DecimalFormat(
 2002 Prentice Hall.
All rights reserved.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
return twoDigits.format( hour ) + ":" +
twoDigits.format( minute ) + ":" +
twoDigits.format( second );
}
Outline
Time1.java
// convert to String in standard-time format
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) +
":" + twoDigits.format( minute ) +
":" + twoDigits.format( second ) +
( hour < 12 ? " AM" : " PM" );
}
}
// end class Time1
 2002 Prentice Hall.
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
29
Outline
// Fig. 8.5: TimeTest3.java
// Class TimeTest3 to use imported class Time1
// Java extension packages
import javax.swing.JOptionPane;
// Deitel packages
import com.deitel.jhtp4.ch08.Time1;
import class JOptionPane from
TimeTest3.java
package javax.swing
Line 5
import class
JOptionPane from
public class TimeTest3 {
import class Time1 from packagepackage
// create an object of class Time1 and manipulate it
com.deitel.jhtp4.ch08
javax.swing
public static void main( String args[]
)
// import Time1 class
{
Time1 time = new Time1();
// create Time1 object
time.setTime( 13, 27, 06 ); // set new time
String output =
can declare Time1
"Universal time is: " TimeTest3
+ time.toUniversalString()
+
"\nStandard time is: " + time.toString();
JOptionPane.showMessageDialog( null, output,
"Packaging Class Time1 for Reuse",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
object
Line 8
import class Time1
from package
com.deitel.jhtp4
.ch08
Line 15
TimeTest3 can
declare Time1 object
}
}
// end class TimeTest3
 2002 Prentice Hall.
All rights reserved.
8.6
Initializing Class Objects: Constructors
• Class constructor
– Same name as class
– Initializes instance variables of a class object
– Call class constructor to instantiate object of that class
ref = new ClassName( arguments );
• ref is reference to appropriate data type
• new indicates that new object is created
• ClassName indicates type of object created
• arguments specifies constructor argument values
 2002 Prentice Hall. All rights reserved.
8.7
Using Overloaded Constructors
• Overloaded constructors
– Methods (in same class) may have same name
– Must have different parameter lists
 2002 Prentice Hall. 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
29
30
31
32
33
34
// Fig. 8.6: Time2.java
// Time2 class definition with overloaded constructors.
package com.deitel.jhtp4.ch08;
Time2.java
// Java core packages
import java.text.DecimalFormat;
public class Time2 extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
Outline
Default constructor has no arguments
// Time2 constructor initializes each instance variable
// to zero. Ensures that Time object starts in a
// consistent state.
public Time2()
{
Overloaded constructor
setTime( 0, 0, 0 );
has one int argument
}
// Time2 constructor: hour supplied, minute and second
// defaulted to 0
public Time2( int h )
Second overloaded constructor
{
setTime( h, 0, 0 );
has two int arguments
}
Lines 16-19
Default constructor has
no arguments
Lines 23-26
Overloaded constructor
has one int argument
Lines 30-33
Second overloaded
constructor has two
int arguments
// Time2 constructor: hour and minute supplied, second
// defaulted to 0
public Time2( int h, int m )
{
setTime( h, m, 0 );
}
 2002 Prentice Hall.
All rights reserved.
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
// Time2 constructor: hour, minute and second supplied
public Time2( int h, int m, int s )
{
Third overloaded constructor
setTime( h, m, s );
has three int arguments
}
Outline
Time2.java
// Time2 constructor: another Time2 object supplied
public Time2( Time2 time )
{
setTime( time.hour, time.minute, time.second );
}
Lines 36-39
Third overloaded
constructor has three
int arguments
Fourth overloaded constructor
// Set a new time value using universal time. Perform
has Time2 argument
// validity checks on data. Set invalid values to zero.
Lines 42-45
public void setTime( int h, int m, int s )
Fourth overloaded
{
constructor has Time2
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
argument
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
}
// convert to String in universal-time format
public String toUniversalString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
return twoDigits.format( hour ) + ":" +
twoDigits.format( minute ) + ":" +
twoDigits.format( second );
}
// convert to String in standard-time format
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
 2002 Prentice Hall.
All rights reserved.
70
71
72
73
74
75
76
77
return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) +
":" + twoDigits.format( minute ) +
":" + twoDigits.format( second ) +
( hour < 12 ? " AM" : " PM" );
Outline
Time2.java
}
}
// end class Time2
 2002 Prentice Hall.
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
29
30
31
32
33
Outline
// Fig. 8.7: TimeTest4.java
// Using overloaded constructors
// Java extension packages
import javax.swing.*;
TimeTest4.java
// Deitel packages
import com.deitel.jhtp4.ch08.Time2;
Line 15
Declare six references
to Time2 objects
public class TimeTest4 {
Declare six references to Time2 objects
// test constructors of class Time2
Lines 17-22
public static void main( String args[] )Instantiate each Time2 reference
Instantiate each Time2
{
using
a
different
constructor
Time2 t1, t2, t3, t4, t5, t6;
reference using a
t1
t2
t3
t4
t5
t6
=
=
=
=
=
=
new
new
new
new
new
new
Time2();
Time2( 2 );
Time2( 21, 34 );
Time2( 12, 25, 42 );
Time2( 27, 74, 99 );
Time2( t4 );
String output
"\nt1: all
"\n
"
"\n
"
//
//
//
//
//
//
00:00:00
02:00:00
21:34:00
12:25:42
00:00:00
12:25:42
different constructor
= "Constructed with: " +
arguments defaulted" +
+ t1.toUniversalString() +
+ t1.toString();
output += "\nt2: hour specified; minute and " +
"second defaulted" +
"\n
" + t2.toUniversalString() +
"\n
" + t2.toString();
 2002 Prentice Hall.
All rights reserved.
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
output += "\nt3: hour and minute specified; " +
"second defaulted" +
"\n
" + t3.toUniversalString() +
"\n
" + t3.toString();
Outline
TimeTest4.java
output += "\nt4: hour, minute, and second specified" +
"\n
" + t4.toUniversalString() +
"\n
" + t4.toString();
output += "\nt5: all invalid values specified" +
"\n
" + t5.toUniversalString() +
"\n
" + t5.toString();
output += "\nt6: Time2 object t4 specified" +
"\n
" + t6.toUniversalString() +
"\n
" + t6.toString();
JOptionPane.showMessageDialog( null, output,
"Demonstrating Overloaded Constructors",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class TimeTest4
 2002 Prentice Hall.
All rights reserved.
Outline
TimeTest4.java
Different outputs,
because each Time2
reference was
instantiated with a
different constructor
Different outputs, because each
Time2 reference was instantiated
with a different constructor
 2002 Prentice Hall.
All rights reserved.
8.8
Using Set and Get Methods
• Accessor method (“get” method)
– public method
– Allow clients to read private data
• Mutator method (“set” method)
– public method
– Allow clients to modify private data
 2002 Prentice Hall. 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
29
30
31
32
33
34
// Fig. 8.8: Time3.java
// Time3 class definition with set and get methods
package com.deitel.jhtp4.ch08;
Time3.java
// Java core packages
import java.text.DecimalFormat;
public class Time3 extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
Outline
Lines 9-11
private variables
private variables cannot be cannot be accessed
accessed directly by objects in directly by objects in
different classes
different
classes
instance
variable
// Time3 constructor initializes each
// to zero. Ensures that Time object starts in a
// consistent state.
public Time3()
{
setTime( 0, 0, 0 );
}
// Time3 constructor: hour supplied, minute and second
// defaulted to 0
public Time3( int h )
{
setTime( h, 0, 0 );
}
// Time3 constructor: hour and minute supplied, second
// defaulted to 0
public Time3( int h, int m )
{
setTime( h, m, 0 );
}
 2002 Prentice Hall.
All rights reserved.
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
// Time3 constructor: hour, minute and second supplied
public Time3( int h, int m, int s )
{
setTime( h, m, s );
}
Outline
Time3.java
// Time3 constructor: another Time3 object supplied
public Time3( Time3 time )
{
setTime( time.getHour(), time.getMinute(),
time.getSecond() );
Mutator methods
}
Lines 51-68
Mutator methods
allows objects to
manipulate private
allows objects to
manipulate private variablesvariables
// Set Methods
// Set a new time value using universal time. Perform
// validity checks on data. Set invalid values to zero.
public void setTime( int h, int m, int s )
{
setHour( h );
// set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
}
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
}
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
}
 2002 Prentice Hall.
All rights reserved.
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// validate and set second
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
}
// Get Methods
// get hour value
public int getHour()
{
return hour;
}
Accessor methods allows objects
to read private variables
Outline
Time3.java
Lines 78-93
Accessor methods
allows objects to read
private variables
// get minute value
public int getMinute()
{
return minute;
}
// get second value
public int getSecond()
{
return second;
}
// convert to String in universal-time format
public String toUniversalString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
return twoDigits.format( getHour() ) + ":" +
twoDigits.format( getMinute() ) + ":" +
twoDigits.format( getSecond() );
}
 2002 Prentice Hall.
All rights reserved.
105
106
107
108
109
110
111
112
113
114
115
116
117
// convert to String in standard-time format
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
Outline
Time3.java
return ( ( getHour() == 12 || getHour() == 0 ) ?
12 : getHour() % 12 ) + ":" +
twoDigits.format( getMinute() ) + ":" +
twoDigits.format( getSecond() ) +
( getHour() < 12 ? " AM" : " PM" );
}
}
// end class Time3
 2002 Prentice Hall.
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
29
30
31
32
33
34
// Fig. 8.9: TimeTest5.java
// Demonstrating the Time3 class set and get methods.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
// Deitel packages
import com.deitel.jhtp4.ch08.Time3;
Outline
TimeTest5.java
Declare and instantiate
Time3 object
Lines 17 and 26
Declare and instantiate
Time3 object
public class TimeTest5 extends JApplet
implements ActionListener {
private Time3 time;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField,
secondField, displayField;
private JButton tickButton;
// Create Time3 object and set up GUI
public void init()
{
time = new Time3();
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up hourLabel and hourField
hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 );
hourField.addActionListener( this );
 2002 Prentice Hall.
All rights reserved.
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
Outline
container.add( hourLabel );
container.add( hourField );
// set up minuteLabel and minuteField
minuteLabel = new JLabel( "Set minute" );
minuteField = new JTextField( 10 );
minuteField.addActionListener( this );
container.add( minuteLabel );
container.add( minuteField );
TimeTest5.java
Lines 39-55
JTextFields allow
JTextFields allow
user to specify time
user to specify time
// set up secondLabel and secondField
secondLabel = new JLabel( "Set Second" );
secondField = new JTextField( 10 );
secondField.addActionListener( this );
container.add( secondLabel );
container.add( secondField );
// set up displayField
displayField = new JTextField( 30 );
displayField.setEditable( false );
container.add( displayField );
// set up tickButton
tickButton = new JButton( "Add 1 to Second" );
tickButton.addActionListener( this );
container.add( tickButton );
updateDisplay();
// update text in displayField
}
// handle button and text field events
public void actionPerformed( ActionEvent actionEvent )
{
 2002 Prentice Hall.
All rights reserved.
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Outline
// process tickButton event
if ( actionEvent.getSource() == tickButton )
tick();
// process hourField event
else if ( actionEvent.getSource() == hourField ) {
time.setHour(
Integer.parseInt( actionEvent.getActionCommand() ) );
hourField.setText( "" );
}
// process minuteField event
else if ( actionEvent.getSource() == minuteField ) {
time.setMinute(
Integer.parseInt( actionEvent.getActionCommand() ) );
minuteField.setText( "" );
}
TimeTest5.java
Lines 74-76
Lines 81-83
Lines 88-90
TimeTest5 uses
Time3 mutator
methods to set Time3
private variables
TimeTest5 uses Time3
mutator methods to set
) Time3
{
private variables
// process secondField event
else if ( actionEvent.getSource() == secondField
time.setSecond(
Integer.parseInt( actionEvent.getActionCommand() ) );
secondField.setText( "" );
}
updateDisplay();
// update displayField and status bar
}
// update displayField and applet container's status bar
public void updateDisplay()
{
displayField.setText( "Hour: " + time.getHour() +
"; Minute: " + time.getMinute() +
"; Second: " + time.getSecond() );
 2002 Prentice Hall.
All rights reserved.
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
Outline
showStatus( "Standard time is: " + time.toString() +
"; Universal time is: " + time.toUniversalString() );
}
// add one to second and update hour/minute if necessary
public void tick()
{
time.setSecond( ( time.getSecond() + 1 ) % 60 );
if ( time.getSecond() == 0 ) {
time.setMinute( ( time.getMinute() + 1 ) % 60 );
if ( time.getMinute() == 0 )
time.setHour( ( time.getHour() + 1 ) % 24 );
TimeTest5.java
Lines 110-116
TimeTest5 uses
Time3 accessor
methods to read Time3
private variables
}
}
}
// end class TimeTest5
TimeTest5 uses Time3
accessor methods to read
Time3 private variables
 2002 Prentice Hall.
All rights reserved.
Outline
TimeTest5.java
 2002 Prentice Hall.
All rights reserved.
Outline
TimeTest5.java
 2002 Prentice Hall.
All rights reserved.
Outline
TimeTest5.java
 2002 Prentice Hall.
All rights reserved.
8.8.1 Executing an Applet that Uses
Programmer-Defined Packages
• appletviewer
– Runs Fig. 8.8 and Fig. 8.9
– Good for testing applets that (eventually) run in browsers
• jar
– Java archive utility
– Bundles classes and packages
• Classes and packages are downloaded as one unit (JAR file)
– Client makes only one call to server
 2002 Prentice Hall. All rights reserved.
Outline
TimeTest5.jar
0
71
2959
0
0
0
1765
Fri
Fri
Fri
Fri
Fri
Fri
Fri
May
May
May
May
May
May
May
25
25
25
18
18
18
18
14:13:14
14:13:14
13:42:32
17:35:18
17:35:18
17:35:18
17:35:18
EDT
EDT
EDT
EDT
EDT
EDT
EDT
2001
2001
2001
2001
2001
2001
2001
META-INF/
META-INF/MANIFEST.MF
TimeTest5.class
com/deitel/
com/deitel/jhtp4/
com/deitel/jhtp4/ch08/
com/deitel/jhtp4/ch08/Time3.class
Fig. 8.10 Contents of TimeTest5.jar.
 2002 Prentice Hall.
All rights reserved.
8.9
Software Reusability
• Java
– Framework for achieving software reusability
– Rapid applications development (RAD)
• e.g., creating a GUI application quickly
 2002 Prentice Hall. All rights reserved.
8.10 Final Instance Variables
• final keyword
– Indicates that variable is not modifiable
• Any attempt to modify final variable results in error
private final int INCREMENT = 5;
• Declares variable INCREMENT as a constant
– Enforces principle of least privilege
 2002 Prentice Hall. 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
29
30
31
32
33
34
35
Outline
// Fig. 8.11: Increment.java
// Initializing a final variable
// Java core packages
import java.awt.*;
import java.awt.event.*;
Increment.java
final keyword declares
INCREMENT as constant
// Java extension packages
import javax.swing.*;
public class Increment extends JApplet
implements ActionListener {
private int count = 0, total = 0;
private final int INCREMENT = 5;
private JButton button;
//
Line 15
final keyword
declares INCREMENT
as constant
Line 32
constant variable
final variable
INCREMENT must be
initialized before using
final variable INCREMENT
it
must be initialized before using it
// set up GUI
public void init()
{
Container container = getContentPane();
button = new JButton( "Click to increment" );
button.addActionListener( this );
container.add( button );
}
// add INCREMENT to total when user clicks button
public void actionPerformed( ActionEvent actionEvent )
{
total += INCREMENT;
count++;
showStatus( "After increment " + count +
": total = " + total );
 2002 Prentice Hall.
All rights reserved.
36
37
38
}
}
Outline
// end class Increment
Increment.java
Increment.java:11: variable INCREMENT might not have been initialized
public class Increment extends Japplet
^
Compiler error
message as a result
of not initializing
increment.
1 error
 2002 Prentice Hall.
All rights reserved.
8.11 Composition: Objects as Instance
Variables of Other Classes
• Composition
– Class contains references to objects of other classes
• These references are members
 2002 Prentice Hall. 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
29
30
31
32
33
34
35
// Fig. 8.13: Date.java
// Declaration of the Date class.
package com.deitel.jhtp4.ch08;
public class Date extends
private int month; //
private int day;
//
private int year;
//
Class Date encapsulates
data that describes date
Object {
1-12
1-31 based on month
any year
Outline
Date.java
Line 5
Class Date
encapsulates data that
describes date
// Constructor: Confirm proper value for month;
// call method checkDay to confirm proper
// value for day.
public Date( int theMonth, int theDay, int theYear )
{
Lines 13-28
if ( theMonth > 0 && theMonth <= 12 ) // validate month
Date constructor
month = theMonth;
instantiates Date
else {
Date constructor instantiates
month = 1;
object based on
System.out.println( "Month " + theMonth +
Date object based
on arguments
specified
" invalid. Set to month 1." );
specified arguments
}
year = theYear;
day = checkDay( theDay );
// could validate year
// validate day
System.out.println(
"Date object constructor for date " + toString() );
}
// Utility method to confirm proper day value
// based on month and year.
private int checkDay( int testDay )
{
int daysPerMonth[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
 2002 Prentice Hall.
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// check if day in range for month
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
Outline
Date.java
// check for leap year
if ( month == 2 && testDay == 29 &&
( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
System.out.println( "Day " + testDay +
" invalid. Set to day 1." );
return 1;
// leave object in consistent state
}
// Create a String of the form month/day/year
public String toString()
{
return month + "/" + day + "/" + year;
}
}
// end class Date
 2002 Prentice Hall.
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
29
30
Outline
// Fig. 8.14: Employee.java
// Definition of class Employee.
package com.deitel.jhtp4.ch08;
Employee.java
public class Employee extends Object {
private String firstName;
private String lastName;
private Date birthDate;
private Date hireDate;
Employee is composed of two Lines 9-10
references to Date objects Employee is composed
of two references to
birth date and hire date
Date objects
// constructor to initialize name,
public Employee( String first, String last,
int birthMonth, int birthDay, int birthYear,
int hireMonth, int hireDay, int hireYear )
instantiate Date objects
{
firstName = first;
calling constructors
lastName = last;
birthDate = new Date( birthMonth, birthDay, birthYear );
hireDate = new Date( hireMonth, hireDay, hireYear );
}
by
Lines 18-19
instantiate Date
objects by calling
constructors
// convert Employee to String format
public String toString()
{
return lastName + ", " + firstName +
" Hired: " + hireDate.toString() +
" Birthday: " + birthDate.toString();
}
}
// end class Employee
 2002 Prentice Hall.
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
// Fig. 8.15: EmployeeTest.java
// Demonstrating an object with a member object.
// Java extension packages
import javax.swing.JOptionPane;
Outline
EmployeeTest.jav
a
// Deitel packages
import com.deitel.jhtp4.ch08.Employee;
public class EmployeeTest {
// test class Employee
public static void main( String args[] )
{
Employee employee = new Employee( "Bob", "Jones",
7, 24, 49, 3, 12, 88 );
JOptionPane.showMessageDialog( null,
employee.toString(), "Testing Class Employee",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class EmployeeTest
 2002 Prentice Hall.
All rights reserved.
Outline
EmployeeTest.jav
a
Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
 2002 Prentice Hall.
All rights reserved.
8.12 Package Access
• Package access
– Variable or method does not have member access modifier
 2002 Prentice Hall. 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
29
30
31
32
33
34
35
// Fig. 8.16: PackageDataTest.java
// Classes in the same package (i.e., the same directory) can
// use package access data of other classes in the same package.
// Java extension packages
import javax.swing.JOptionPane;
Instantiate reference to
PackageData object
public class PackageDataTest {
// Java extension packages
public static void main( String args[] )
{
PackageData packageData = new PackageData();
Outline
PackageDataTest.
java
Line 13
Instantiate reference to
PackageData object
Lines 17-25
// append String representation of packageData to output
PackageDataTest
String output =
can access can
"After instantiation:\n" + packageData.toString();
PackageDataTest
PackageData data,
access PackageData
// change package access data in packageData object
because
data, because
each each
class class
packageData.number = 77;
shares
same package
packageData.string = "Good bye";
shares same
package
// append String representation of packageData to output
output += "\nAfter changing values:\n" +
packageData.toString();
JOptionPane.showMessageDialog( null, output,
"Demonstrating Package Access",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class PackageDataTest
 2002 Prentice Hall.
All rights reserved.
36 // class with package-access instance variables
37 class PackageData {
38
int number;
// package-access instance variable
39
String string; // package-access instance variable
40
41
// constructor
42
public PackageData()
No access modifier, so class
43
{
has package-access variables
44
number = 0;
45
string = "Hello";
46
}
47
48
// convert PackageData object to String representation
49
public String toString()
50
{
51
return "number: " + number + "
string: " + string;
52
}
53
54 } // end class PackageData
Outline
PackageDataTest.
java
Line 37
No access modifier, so
class has packageaccess variables
 2002 Prentice Hall.
All rights reserved.
8.13 Using the this Reference
• This reference
– Allows an object to refers to itself
 2002 Prentice Hall. 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
29
30
// Fig. 8.17: ThisTest.java
// Using the this reference to refer to
// instance variables and methods.
// Java core packages
import java.text.DecimalFormat;
Outline
ThisTest.java
// Java extension packages
import javax.swing.*;
public class ThisTest {
// test class SimpleTime
public static void main( String args[] )
{
SimpleTime time = new SimpleTime( 12, 30, 19 );
JOptionPane.showMessageDialog( null, time.buildString(),
"Demonstrating the \"this\" Reference",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class ThisTest
// class SimpleTime demonstrates the "this" reference
class SimpleTime {
private int hour, minute, second;
 2002 Prentice Hall.
All rights reserved.
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 }
// constructor uses parameter names identical to instance
// variable names, so "this" reference required to distinguish
// between instance variables and parameters
public SimpleTime( int hour, int minute, int second )
{
this
used to distinguish
this.hour = hour;
// set "this" object's
hour
this.minute = minute; // set "this" object's
minutearguments and
between
this.second = second; // set "this" object's second
ThisTest variables
}
// call toString explicitly via "this" reference, explicitly
// via implicit "this" reference, implicitly via "this"
public String buildString()
{
return "this.toString(): " + this.toString() +
"\ntoString(): " + toString() +
"\nthis (with implicit toString() call): " + this;
}
// convert SimpleTime to String format
Implicit
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
Outline
ThisTest.java
Lines 36-37
this used to
distinguish between
arguments and
ThisTest variables
Lines 45, 57-59
Implicit use of this
use of this
// "this" not required, because toString does not have
// local variables with same names as instance variables
return twoDigits.format( this.hour ) + ":" +
twoDigits.format( this.minute ) + ":" +
twoDigits.format( this.second );
}
// end class SimpleTime
 2002 Prentice Hall.
All rights reserved.
Outline
ThisTest.java
 2002 Prentice Hall.
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
29
30
31
32
33
34
// Fig. 8.18: Time4.java
// Time4 class definition
package com.deitel.jhtp4.ch08;
// Java core packages
import java.text.DecimalFormat;
Outline
Time4.java
public class Time4 extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
// Time4 constructor initializes each instance variable
// to zero. Ensures that Time object starts in a
// consistent state.
public Time4()
{
this.setTime( 0, 0, 0 );
}
// Time4 constructor: hour supplied, minute and second
// defaulted to 0
public Time4( int hour )
{
this.setTime( hour, 0, 0 );
}
// Time4 constructor: hour and minute supplied, second
// defaulted to 0
public Time4( int hour, int minute )
{
this.setTime( hour, minute, 0 );
}
 2002 Prentice Hall.
All rights reserved.
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
// Time4 constructor: hour, minute and second supplied
public Time4( int hour, int minute, int second )
{
this.setTime( hour, minute, second );
}
Outline
Time4.java
// Time4 constructor: another Time4 object supplied.
Lines 56 and 64
public Time4( Time4 time )
Method returns this
{
reference to enable
this.setTime( time.getHour(), time.getMinute(),
Method
returns
this (concatenated
time.getSecond() );
chaining
}
reference to enable chaining
method calls)
(concatenated method calls)
// Set Methods
// set a new Time value using universal time
public Time4 setTime( int hour, int minute, int second )
{
this.setHour( hour );
// set hour
this.setMinute( minute ); // set minute
this.setSecond( second ); // set second
return this;
// enables chaining
}
// validate and set hour
public Time4 setHour( int hour )
{
this.hour = ( hour >= 0 && hour < 24 ? hour : 0 );
return this;
// enables chaining
}
 2002 Prentice Hall.
All rights reserved.
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// validate and set minute
public Time4 setMinute( int minute )
{
this.minute =
( minute >= 0 && minute < 60 ) ? minute : 0;
return this;
// enables chaining
}
Outline
Time4.java
Method returns this Lines 73 and 82
Method returns this
reference to enable chaining
reference to enable
(concatenated method calls)
chaining (concatenated
method calls)
// validate and set second
public Time4 setSecond( int second )
{
this.second =
( second >= 0 && second < 60 ) ? second : 0;
return this;
// enables chaining
}
// Get Methods
// get value of hour
public int getHour() { return this.hour; }
// get value of minute
public int getMinute() { return this.minute; }
// get value of second
public int getSecond() { return this.second; }
// convert to String in universal-time format
public String toUniversalString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
 2002 Prentice Hall.
All rights reserved.
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 }
return twoDigits.format( this.getHour() ) + ":" +
twoDigits.format( this.getMinute() ) + ":" +
twoDigits.format( this.getSecond() );
}
Outline
Time4.java
// convert to String in standard-time format
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat( "00" );
return ( this.getHour() == 12 || this.getHour() == 0 ?
12 : this.getHour() % 12 ) + ":" +
twoDigits.format( this.getMinute() ) + ":" +
twoDigits.format( this.getSecond() ) +
( this.getHour() < 12 ? " AM" : " PM" );
}
// end class Time4
 2002 Prentice Hall.
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
29
30
31
32
33
34
35
// Fig. 8.19: TimeTest6.java
// Chaining method calls together with the this reference
// Java extension packages
import javax.swing.*;
// Deitel packages
import com.deitel.jhtp4.ch08.Time4;
Declare and instantiate
reference to Time4 object
public class TimeTest6 {
Outline
Time6.java
Line 15
Declare and instantiate
reference to Time4
Concatenate (chain) object
Time4
// test method call chaining with object of class Time4
public static void main( String args[] )
method calls, because methods
Lines 18 and 26
{
return Time4 reference
Time4 time = new Time4();
Concatenate (chain)
// chain calls to setHour, setMinute and setSecond
time.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
// use method call chaining to set new time and get
// String representation of new time
String output =
"Universal time: " + time.toUniversalString() +
"\nStandard time: " + time.toString() +
"\n\nNew standard time: " +
time.setTime( 20, 20, 20 ).toString();
Time4 method calls,
because methods return
Time4 reference
JOptionPane.showMessageDialog( null, output,
"Chaining Method Calls",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class TimeTest6
 2002 Prentice Hall.
All rights reserved.
Outline
Time6.java
 2002 Prentice Hall.
All rights reserved.
8.14 Finalizers
• Garbage collection
– Returns memory to system
– Java performs this automatically
• object marked for garbage collection if no references to object
• Finalizer method
– Returns resources to system
– Java provides method finalize
• Defined in java.lang.Object
• Receives no parameters
• Returns void
 2002 Prentice Hall. All rights reserved.
8.15 Static Class Members
• static keyword
– static class variable
• Class-wide information
– All class objects share same data
 2002 Prentice Hall. All rights reserved.
Outline
1 // Fig. 8.20: Employee.java
2 // Employee class definition.
Employee objects share one
3 public class Employee extends Object {
4
private String firstName;
instance of count
Employee.java
5
private String lastName;
6
private static int count; // number of objects in memory
7
Line 6
8
// initialize employee, add 1 to static count and
Employee objects
9
// output String indicating that constructor was called
share one instance of
10
public Employee( String first, String last )
11
{
count
12
firstName = first;
13
lastName = last;
Lines 23-28
14
15
++count; // increment static count of employees
Called when
16
System.out.println( "Employee object constructor: " +
Employee is marked
17
firstName + " " + lastName );
Called
when
Employee
is
for garbage collection
18
}
marked for garbage collection
19
20
// subtract 1 from static count when garbage collector
21
// calls finalize to clean up object and output String
22
// indicating that finalize was called
23
protected void finalize()
24
{
25
--count; // decrement static count of employees
26
System.out.println( "Employee object finalizer: " +
27
firstName + " " + lastName + "; count = " + count );
28
}
29
30
// get first name
31
public String getFirstName()
32
{
33
return firstName;
34
}
 2002 Prentice Hall.
35
All rights reserved.
36
37
38
39
40
41
42
43
44
45
46
47
48 }
// get last name
public String getLastName()
{
return lastName;
}
Outline
static method accesses
static variable count
// static method to get static count value
public static int getCount()
{
return count;
}
Employee.java
Lines 43-46
static method
accesses static
variable count
// end class Employee
 2002 Prentice Hall.
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
29
30
31
// Fig. 8.21: EmployeeTest.java
// Test Employee class with static class variable,
// static class method, and dynamic memory.
import javax.swing.*;
Outline
EmployeeTest can invoke Employee EmployeeTest.jav
a
static method, even though
public class EmployeeTest {
Employee has not been instantiated
// test class Employee
Line 13
public static void main( String args[] )
EmployeeTest can
{
// prove that count is 0 before creating Employees
invoke Employee
String output = "Employees before instantiation: " +
static method, even
Employee.getCount();
though Employee has
// create two Employees; count should be 2
not been instantiated
Employee e1 = new Employee( "Susan", "Baker" );
Employee e2 = new Employee( "Bob", "Jones" );
// Prove that count is 2 after creating two Employees.
// Note: static methods should be called only via the
// class name for the class in which they are defined.
output += "\n\nEmployees after instantiation: " +
"\nvia e1.getCount(): " + e1.getCount() +
"\nvia e2.getCount(): " + e2.getCount() +
"\nvia Employee.getCount(): " + Employee.getCount();
// get names of Employees
output += "\n\nEmployee 1: " + e1.getFirstName() +
" " + e1.getLastName() + "\nEmployee 2: " +
e2.getFirstName() + " " + e2.getLastName();
 2002 Prentice Hall.
All rights reserved.
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
//
//
//
//
//
e1
e2
If there is only one reference to each employee (as
on this example), the following statements mark
those objects for garbage collection. Otherwise,
these statement simply decrement the reference count
for each object.
Calls Java’s automatic garbage= null;
= null;
collection mechanism
System.gc(); // suggest call to garbage collector
// Show Employee count after calling garbage collector.
// Count displayed may be 0, 1 or 2 depending on
// whether garbage collector executed immediately and
// number of Employee objects it collects.
output += "\n\nEmployees after System.gc(): " +
Employee.getCount();
Outline
EmployeeTest.jav
a
Line 40
Calls Java’s automatic
garbage-collection
mechanism
JOptionPane.showMessageDialog( null, output,
"Static Members and Garbage Collection",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
// end class EmployeeTest
Employee
Employee
Employee
Employee
object
object
object
object
constructor: Susan Baker
constructor: Bob Jones
finalizer: Susan Baker; count = 1
finalizer: Bob Jones; count = 0
 2002 Prentice Hall.
All rights reserved.
Outline
EmployeeTest.jav
a
 2002 Prentice Hall.
All rights reserved.
8.16 Data Abstraction and Encapsulation
• Encapsulation (data hiding)
– Stack data structure
• Last in-first out (LIFO)
• Developer creates stack
– Hides stack’s implementation details from clients
• Data abstraction
– Abstract data types (ADTs)
 2002 Prentice Hall. All rights reserved.
8.16.1 Example: Queue Abstract Data Type
• Abstract Data Type (ADT)
– Queue
• Line at grocery store
• First-in, first-out (FIFO)
– Enqueue to place objects in queue
– Dequeue to remove object from queue
– Enqueue and dequeue hide internal data representation
 2002 Prentice Hall. All rights reserved.
8.17 (Optional Case Study) Thinking About
Objects: Starting to Program the Classes for
the Elevator Simulation
• Visibility
– Apply member-access modifiers to class members
– public methods
• to provide services to clients
– private variables
• To promote encapsulation
 2002 Prentice Hall. All rights reserved.
8.17 Thinking About Objects (cont.)
• Class diagram (UML)
– Member-access modifiers
• public
– Denoted by plus sign (+)
• private
– Denoted by minus sign (-)
 2002 Prentice Hall. All rights reserved.
Fig 8.13 Complete class diagram with visibility notations.
ElevatorModel
- numberPeople : Integer = 0
+ addPerson( ) : void
Person
- ID : Integer
- moving : Boolean = true
+ doorOpened( ) : void
ElevatorShaft
<none yet>
<none yet>
ElevatorDoor
- open : Boolean = false
+ openDoor( ) : void
+ closeDoor( ) : void
Floor
- floorNumber : Integer
- capacity : Integer = 1
<none yet>
Light
- lightOn : Boolean = false
+ turnOnLight( ) : void
+ turnOffLight( ) : void
Elevator
- moving : Boolean = false
- summoned:Boolean = false
- currentFloor : Integer = 1
- destinationFloor:Integer = 2
- capacity : Integer = 1
- travelTime : Integer = 5
+ ride( ) : void
+ requestElevator( ) : void
+ enterElevator( ) : void
+ exitElevator( ) : void
+ departElevator( ) : void
 2002 Prentice Hall. All rights reserved.
ElevatorButton
- pressed : Boolean = false
+ resetButton( ) : void
+ pressButton( ) : void
FloorButton
- pressed : Boolean = false
+ resetButton( ) : void
+ pressButton( ) : void
Bell
<none yet>
+ ringBell( ) : void
FloorDoor
- open : Boolean = false
+ openDoor( ) : void
+ closeDoor( ) : void
8.17 Thinking About Objects (cont.)
• Implementation
– Forward engineering
• Transform design (i.e., class diagram) to code
 2002 Prentice Hall. All rights reserved.
8.17 Thinking About Objects (cont.)
• We generate “skeleton code” with our design
– Use class Elevator as example
– Four steps:
• Use name in first compartment to declare public class
– Empty constructor
• Use second compartment to declare member variables
• Use class diagram associations (Fig. 3.23) for object references
• Use third compartment to declare methods
 2002 Prentice Hall. All rights reserved.
8.17 Thinking About Objects (cont.)
Step 1
public class Elevator {
public Elevator() {}
}
 2002 Prentice Hall. All rights reserved.
8.17 Thinking About Objects (cont.)
Step 2
public class Elevator {
// class attributes
private boolean moving;
private boolean summoned;
private int currentFloor = 1;
private int destinationFloor = 2;
private int capacity = 1;
private int travelTime = 5;
// class constructor
public Elevator() {}
}
 2002 Prentice Hall. All rights reserved.
8.17 Thinking About Objects (cont.)
Step 3
public class Elevator {
// class attributes
private boolean moving;
private boolean summoned;
private int currentFloor = 1;
private int destinationFloor = 2;
private int capacity = 1;
private int travelTime = 5;
// class objects
private ElevatorDoor elevatorDoor;
private ElevatorButton elevatorButton;
private Bell bell;
// class constructor
public Elevator() {}
}
 2002 Prentice Hall. All rights reserved.
8.17 Thinking About Objects (cont.)
Step 4
public class Elevator {
// class attributes
private boolean moving;
private boolean summoned;
private int currentFloor = 1;
private int destinationFloor = 2;
private int capacity = 1;
private int travelTime = 5;
// class objects
private ElevatorDoor elevatorDoor;
private ElevatorButton elevatorButton;
private Bell bell;
// class constructor
public Elevator() {}
// class methods
public void ride() {}
public void requestElevator() {}
public void enterElevator() {}
public void exitElevator() {}
public void departElevator() {}
}
 2002 Prentice Hall. All rights reserved.