Académique Documents
Professionnel Documents
Culture Documents
com
Class Comment
class
Class Name
Data Members
Methods
(incl. Constructor)
<modifiers>
Modifiers
Data Type
private
String
Name
ownerName ;
Method Declaration
<modifier>
<return type>
<method name>
( <parameters>
<statements>
}
Modifier
public
Return Type
void
setOwnerName
ownerName = name;
}
Method Name
Parameter
String
name
Statements
) {
){
Constructor
Class Name
public
Parameter
Bicycle
) {
ownerName = "Unassigned";
}
Statements
args) {
owner1, owner2;
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ) ;
bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( ) ; //Output the information
owner2 = bike2.getOwnerName( ) ;
}
}
System.out.println(owner1
System.out.println(owner2
Multiple Instances
Once the Bicycle class is defined, we can create
multiple instances.
bike1
bike2
Sample Code
: Bicycle
ownerName
Adam Smith
: Bicycle
ownerName
Ben Jones
Bicycle
Bicycle.java
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 void setOwnerName
(String name) {
ownerName = name;
}
}
Page 1
Page 2
//This sample program uses both the Bicycle and Account classes
public static void main(String[]
args) {
Bicycle bike;
Account acct;
String
SecondMain.java
Bicycle.java
Account.java
(compile)
(compile)
(compile)
(run)
class Account {
acct.add(400);
. . .
}
. . .
}
parameter
. . .
argument
The number or
arguments and the
parameters must be
the same
Arguments and
parameters are
paired left to right
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.
Accessibility Example
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
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
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
Sample Matching
class MusicCD {
private String
private String
private String
artist;
title;
id;
= name2;
ident
= artist.substring(0,2) + "-" +
title.substring(0,9);
id
}
...
}
= ident;
Methods: A Deeper
Look
2005 Pearson Education, Inc. All rights reserved.
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
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
1
2
3
4
5
6
7
8
9
10
// MaximumFinder.java
// Programmer-declared method maximum.
import java.util.Scanner;
Outline
MaximumFinder.java
11
12
13
14
15
16
17
18
19
20
21
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
26
Display maximum
value
27
28
29
30
Outline
31
32
33
if ( y > maximumValue )
34
maximumValue = y;
35
Maximum
Finder.java
Compare y and
(2 of 2)
maximumValue
36
37
if ( z > maximumValue )
38
maximumValue = z;
Compare z and
maximumValue
39
40
return maximumValue;
41
//
MaximumFinderTest.java
3
4
9
10
11
Create a MaximumFinder
object
Outline
MaximumFinderTest
.java
maximumFinder.determineMaximum();
} // end main
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
4th Ed Chapter 7 - 41
4th Ed Chapter 7 - 42
student
LibraryCard card2;
st
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
email
jj@javauniv.edu
State of Memory
Sharing an Object
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.
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
f2 = f1.simplify();
return simp;
}
f1
simp
f2
: Fraction
: Fraction
numerator
24
numerator
2
denominator
36
denominator
3
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
4th Ed Chapter 7 - 49
Method
Description
Example
abs( x )
absolute value of x
ceil( x )
cos( x )
exp( x )
exponential method ex
floor( x )
log( x )
sin( x )
sqrt( x )
square root of x
tan( x )
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 );
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)
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.
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.)
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
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.
//
Scope.java
Outline
3
4
Scope.java
private int x = 1;
(1 of 2)
8
9
10
11
12
13
Shadows field x
14
15
16
Display value of
local variable x
17
18
19
20
21
2005 Pearson
Education, Inc. All rights
reserved.
22
23
Outline
24
25
26
27
28
Shadows field x
Scope.java
(2 of 2)
29
30
System.out.printf(
31
32
33
System.out.printf(
34
35
Display value of
local variable x
36
37
38
39
40
System.out.printf(
41
42
43
System.out.printf(
44
Display value of
field x
45
2005 Pearson
Education, Inc. All rights
reserved.
Outline
3
4
9
10
11
ScopeTest.java
2005 Pearson
Education, Inc. All rights
reserved.
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
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)
Rule 1
Rule 2
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
Outline
Correctly calls the square
of int
method
Correctly calls the square of double
method
of int method
2005 Pearson
Education, Inc. All rights
reserved.
1
2
3
4
5
6
7
8
9
10
11
Outline
MethodOverloadTest
.java
2005 Pearson
Education, Inc. All rights
reserved.
1
2
3
4
5
6
Outline
MethodOverload
7
8
9
10
11
12
13
14
15
16
17
18
Error.java
ERROR:
Same method signature
{
return y * y;
}
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.
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 {
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.
Comparing Objects
4th Ed Chapter 5 - 83
2005 Pearson Education, Inc. All rights reserved.
4th Ed Chapter 5 - 84
4th Ed Chapter 5 - 85
4th Ed Chapter 5 - 86
The Semantics of ==
4th Ed Chapter 5 - 87
4th Ed Chapter 5 - 88
1
2
Outline
// GradeBook.java
3
4
7
8
10
{
courseName = name; // initializes courseName
11
12
} // end constructor
13
14
15
16
{
courseName = name; // store the course name
17
18
19
20
21
22
23
24
return courseName;
GradeBook.java
(1 of 2)
Constructor to initialize
courseName variable
25
Outline
// display a welcome message to the GradeBook user
26
27
28
29
30
31
32
getCourseName() );
33
34
35 } // end class GradeBook
GradeBook.java
(2 of 2)
1
2
3
// GradeBookTest.java
Outline
4
5
10
11
12
13
14
15
16
17
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
1
2
3
4
5
6
7
8
9
// Account.java
// Account class with a constructor to
// initialize instance variable balance.
Outline
Account.java
double variable
balance
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
} // end method getBalance
29
30 } // end class Account
Outline
1
// AccountTest.java
import java.util.Scanner;
4
5
10
11
12
13
14
15
16
17
account1.getBalance() );
System.out.printf( "account2 balance: $%.2f\n\n",
account2.getBalance() );
18
AccountTest.java
(1 of 3)
19
20
21
Outline
22
23
24
25
26
27
depositAmount );
28
29
// display balances
30
31
32
33
account1.getBalance() );
System.out.printf( "account2 balance: $%.2f\n\n",
account2.getBalance() );
34
35
36
37
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.getBalance() );
System.out.printf( "account2 balance: $%.2f\n",
account2.getBalance() );
} // end main
47
Lines 14 - 17
Lines 23 - 25
Lines 30 - 33
Lines 35 - 38
Lines 42 - 45
AccountTest.java
(3 of 3)
AccountTest.java
98
Example 4
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
Outline
7 {
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
GradeBook6.java
(1 of 3)
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
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
// processing phase
// prompt for input and read grade from user
System.out.print( "Enter grade or -1 to quit: " );
grade = input.nextInt();
56
Outline
while ( grade != -1 )
57
58
59
60
61
62
63
GradeBook6.java
(3 of 3)
grade = input.nextInt();
64
} // end while
65
66
67
// termination phase
68
69
if ( gradeCounter != 0 )
70
71
72
73
74
75
76
77
78
} // end if
79
Calculate average
grade using
(double) to
perform explicit
conversion
Display average
grade
80
81
82
Outline
3
4
10
11
12
13
14
15
GradeBookTest6.java
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
103
Example 5
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
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
Outline
105
GradeBook.java
(2 of 5)
Lines 50-54
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" );
Outline
input
GradeBook.java
(3 of 5)
Line 57
Line 72
controlling
expression
Lines 72-94
(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
83
84
85
86
87
88
89
90
91
92
93
94
Outline
95
96
97
98
99
100
101
102
103
104
105
106
107
GradeBook.java
(4 of 5)
Line 91 default
case
108
109
110
Outline
gradeCounter, total );
111
112
System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n",
113
114
115
116
117
118
119
} // end if
120
121
122
107
GradeBook.java
(5 of 5)
108
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
GradeBookTest.
java
(1 of 2)
Lines 13-15
Outline
110
GradeBookTest.
java
(2 of 2)
Program output
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.
112
113
114
// Time1.java
3
4
Outline
115
// 0 23
No Constructor
9
10
11
12
Time1.jav
a
(1 of 2)
13
14
15
16
17
// validate hour
18
19
20
21
Time1.jav
format strings
a
24
25
26
27
28
29
30
31
116
22
23
Outline
(2 of 2)
117
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
Time1Test.java
(1 of 2)
Call toUniversalString
method
Call toString method
return string
118
18
19
20
21
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
120
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
//
MemberAccessTest.java
8
9
time.hour = 7;
10
11
12
Outline
121
MemberA
ccessTest
.java
// Dialog1.java
Outline
4
5
9
10
11
Import class
JOptionPane
Dialog1.java
Do not explicitly creating an
object because it is
declared as static method
Show a message
dialog with text
1
2
3
//
NameDialog.java
Outline
4
5
10
String name =
11
12
13
14
String message =
15
16
17
18
19
NameDialog.java
Format a String to
output to user
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
129
130
131
132
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
class BicycleRegistration {
public static void main(String[]
args) {
owner1, owner2;
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ) ;
bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( ) ; //Output the information
owner2 = bike2.getOwnerName( ) ;
}
}
System.out.println(owner1
System.out.println(owner2
age;
145
// ThisTest.java
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
146
ThisTest.java
System.out.println( time.buildString() );
(1 of 2)
} // end main
} // end class ThisTest
Declare instance
variables
Method parameters
shadow instance
variables
Constructor
30
31
32
{
return String.format( "%24s: %s\n%24s: %s",
33
"this.toUniversalString()", this.toUniversalString(),
34
"toUniversalString()", toUniversalString() );
35
36
37
38
39
40
41
42
43
44
45
46
147
148
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
Rule 1
Rule 2
151
Overloaded constructors
Provide multiple constructor definitions with different
signatures
No-argument constructor
A constructor invoked without arguments
// Time2.java
2
3
4
5
6
7
8
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
No-argument
constructor
Invoke threeargument
constructor
(1 of 4)
29
30
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
41
32
33
34
35
36
37
38
42
43
44
45
46
// Set Methods
47
setHour( h );
48
49
50
51
52
53
54
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
55
56
57
58
59
60
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
61
62
63
64
65
66
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
67
68
69
70
// Get Methods
71
72
73
74
75
76
return hour;
} // end method getHour
154
77
78
79
80
81
82
83
84
85
86
87
88
89
90
return minute;
} // end method getMinute
155
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
157
158
159
Outline
160
3
4
Call overloaded
constructorsTime2Test
// 00:00:00
// 02:00:00
10
// 21:34:00
11
12
13
// 12:25:42
14
15
16
17
System.out.printf( "
%s\n", t1.toUniversalString() );
18
System.out.printf( "
%s\n", t1.toString() );
19
.java
(1 of 3)
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
31
System.out.printf( "
%s\n", t4.toUniversalString() );
32
System.out.printf( "
%s\n", t4.toString() );
33
34
35
System.out.printf( "
%s\n", t5.toUniversalString() );
36
System.out.printf( "
%s\n", t5.toString() );
37
38
39
System.out.printf( "
%s\n", t6.toUniversalString() );
System.out.printf( "
%s\n", t6.toString() );
40
41
} // end main
Outline
Time2Test.java
(3 of 3)
162
163
164
Review
Customer
customer;
customer
new
customer
1
: Customer
Customer( );
2. A Customer object is
created and the identifier
customer is set to refer to
it.
Class Name
customer
customer : Customer
: Customer
Program Diagram
Notation
State-of-Memory
Notation
customer;
customer
new
Customer( );
customer
new
Customer( );
customer
Created with
the first new.
: Customer
: Customer
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
My
First
true
Java
179
180
181
182
4
5
Declare a
static field
10
11
12
13
14
15
firstName = first;
16
lastName = last;
Increment
static field
17
18
count++;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
183
Declare method
finalize
35
36
37
38
39
40
41
42
43
44
return lastName;
} // end method getLastName
return firstName;
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
184
3
4
10
11
Employee.getCount() );
12
13
14
15
Create new
Employee
objects
185
16
17
18
19
20
21
22
23
24
25
e1.getFirstName(), e1.getLastName(),
26
35
e2.getFirstName(), e2.getLastName() );
Call static
method
getCount
outside objects
186
36
37
38
39
40
41
Employee.getCount() );
} // end main
187
188
189