Chapter 2: Defining a Simple Class

Download Report

Transcript Chapter 2: Defining a Simple Class

An Introduction to
Programming and Object
Oriented Design using Java
2nd Edition. May 2004
Jaime Niño
Frederick Hosch
Chapter 2: Defining a Simple Class
Object Interaction: Clients and Servers
 Objectives: After studying this chapter you should
understand the following:
 the client-server relationship;
 the purpose of a class specification;
 the purpose of a class implementation;
 the function of statements in a program;
 the function of arithmetic expressions in a program;
 the meaning and use of an assignment statement;
 the role of parameters in the specification of a method;
 the role of comments in programs.
May 2004
NH-Chapter 2
1
Object Interaction:
Clients and Servers
 Also, you should be able to:
 write the specification of a simple class;
 implement a simple class;
 invoke an object’s methods;
 construct a simple static diagram;
 construct a simple interaction diagram describing the
interaction of two objects.
 write and evaluate arithmetic expressions;
 write legal return statements;
 write legal assignment statements;
 develop a javadoc document for the client.
May 2004
NH-Chapter 2
2
Clients and Servers
 Recall:
 an object has features: queries and commands.
 objects cooperate to produce a problem solution.
May 2004
NH-Chapter 2
3
Client and Server relationship
query
Piece
Player
color
userControlled
white
currentSquare
yes
d1
color
white
rank
queen
square
…
d1
…
client
response
server
command
Piece
Player
color
userControlled
white
moveTo(c2)
yes
white
rank
queen
square
…
client
color
d1
…
server before executing
command
server after executing
command
Piece
color
white
rank
queen
square
c2
…
May 2004
NH-Chapter 2
4
Clients and Servers
 Object A uses object B
 object A is termed the client, and object B is the server.
 A client queries and commands a server.
May 2004
NH-Chapter 2
5
Clients and Servers
 Example: chess playing program.
 Client Player, Server Piece
Player object queries Piece object to determine its location,
Player object commands Piece to move to new location on board.
May 2004
NH-Chapter 2
6
Server specification and Implementation
 Client need only know server’s features and use.
 Object specification (interface): definition of
object’s features, as seen by its clients.
 The implementation provides the “internals” that
actually make up the features.
May 2004
NH-Chapter 2
7
Example of Client specification
for Counter
 Start listing its responsibilities:
 Class: Counter
 queries:
currentCount the current value of count, a non-negative integer
 commands:
reset set the value of count to 0
incrementCount increment the value of count by 1
May 2004
NH-Chapter 2
8
Defining class Counter in Java
package counters;
/**
* A simple integer counter.
*/
public class Counter {
Definitions of features goes here.
}
May 2004
NH-Chapter 2
9
Specifying a Method for a query
Name of method.
Type of value returned
by query.
/**
* The number of items counted
*/
public int currentCount () {
Method implementation goes here.
}
May 2004
NH-Chapter 2
10
Specifying a Method for a command
Name of method.
Type of value returned
by command.
/**
* The number of items counted
*/
public void incrementCount ()
Method implementation goes here.
}
May 2004
NH-Chapter 2
11
Class constructor
 constructor: a class’ method used to create and
initialize an object.
Name of method.
/**
* Create a new Counter, with the
count initialized to 0
*/
public Counter () {Method implementation goes here.
}
 Note: name of class constructor is the same as
the name of the class.
May 2004
NH-Chapter 2
12
Static diagram of the class Counter
Counter
+int currentCount()
+void incrementCount()
+void reset()
May 2004
NH-Chapter 2
13
Invoking queries
 client’s reference object to Counter: myCounter
 To query myCounter for current value of count:
myCounter.currentCount()
server
client
Counter
int count
myCounter.currentCount()
public
4
currentCount () {
.
.
4
1. client invokes the method
currentCount of the object myCounter.
int
myCounter
}
2. object myCounter performs actions as
prescribed by the method definition.
3. the result of myCounter executing the method is that the
value of the current count is delivered to the client.
May 2004
NH-Chapter 2
14
Invoking commands
 client’s reference object to Counter: myCounter
 To command myCounter to reset,
myCounter.reset();
Counter
Server’s state
Before command
void reset {
2. myCounter performs actions as prescribed
by method
myCounter.reset();
Counter
1. client invokes the method
reset of the object myCounter.
May 2004
4
int count
public
.
.
}
client
myCounter
Server’s state
after command
NH-Chapter 2
myCounter
int count
.
public
.
.
}
.
}
0
void reset {
15
Interaction diagrams
 client object interacting with a Counter.
object queries Counter for current count, and then
give Counter command reset.
Client
Counter
currentCount()
time
the object is active
executing the method
count
currentCount
reset()
May 2004
NH-Chapter 2
16
Implementing class data
 Counter needs current value of count.
 Define only one instance variable: syntax to use
private variableType variableName;
 Variable definition is included in class:
public class Counter {
private int count;
// current count
…
}
May 2004
NH-Chapter 2
17
Counter
Type of variable
int
count
10
Value of variable at
some time
Name of variable
Instance variable
Counter object showing instance variable
Counter
-int count
+int currentCount()
+void incrementCount()
+void reset()
Static diagram of class Counter, showing instance variable
May 2004
NH-Chapter 2
18
Implementing functionality
 For each method provide algorithm
 set of instructions for processor to carrys out.
 Algorithm is described via Java statements:
 statement: a language construct that describes an action
for the processor to execute.
May 2004
NH-Chapter 2
19
Implementing query currentCount
 Method must deliver value stored in variable count.
 Use return statement: return count;
/**
* The number of items counted.
*/
public int currentCount () {
return count;
}
May 2004
NH-Chapter 2
20
Return statement and expressions
The general form of a return statement is
return expression;
 Expression : language construct that describes how
to compute a particular value.
 Processor evaluates expression to produce a value.
May 2004
NH-Chapter 2
21
Implementing simple
commands:Assignment statement
A command modifies state of the object.
Use an assignment statement:
instructs processor to compute a value and store it in a variable.
LHS
variableName = expression;
RHS
 Processor executes assignment in two steps:
1. computes the value by the expression on RHS;
2. stores value in variable on LHS, replacing previous
value.
May 2004
NH-Chapter 2
22
Implementing command reset
 want to store 0 in the variable count.
/**
* Reset the count to 0.
*/
public void reset () {
count = 0;
}
May 2004
NH-Chapter 2
23
Implementing the command
incrementCount
 want to update count to current value in count plus one.
 Use count on LHS, and
 Use the expression : count + 1 on RHS
/**
* Increment the count by 1.
*/
public void incrementCount () {
count = count + 1;
}
May 2004
NH-Chapter 2
24
Implementing constructor
 instance variable count must be set to 0 in the
instance creation.
/**
* Create a new Counter, with the count initializ
*/
public Counter () {
count = 0;
}
May 2004
NH-Chapter 2
25
Arithmetic expressions
 Expressions that evaluate to integer and floating
point values.
 Can be built by combining literals and variable
names with arithmetic operators
+
*
/
%
May 2004
addition
subtraction
multiplication
division
remainder
NH-Chapter 2
26
Unary operators: “+” and “-”
 assume that i1, is an int variables containing 10
+3  3
-3
 -3
+ i1  10
- i1  -10
May 2004
NH-Chapter 2
27
Division operator
 “/” denotes division when applied to two floating
point operands, but integer quotient when applied to
two integer operands.
2.0/4.0
2/4
5.0/4.0
5/4
May 2004
 0.5
 0
 1.25
 1
NH-Chapter 2
28
Remainder operator %
 Primarily used with integer
operands
10
10
10
10
May 2004
%
%
%
%
5

3

6

11  10
NH-Chapter 2
0
1
4
29
Mixed type expressions
Numeric promotion
 Mixed Operands:
 what happens if one operand is int and the other
double,
 int operand is converted (promoted) to a double
representing same value
7 / 2.0

7.0 / 2.0

3.5
i1 * 0.5
 10 * 0.5
 10.0 * 0.5
May 2004
NH-Chapter 2
30
Operator precedence
What is the order of evaluation in
5 + 10 * 2
 Unary + and – have higher precedence than binary
operators.
 *, /, % have higher precedence than operators +,-
May 2004
NH-Chapter 2
31
Operator precedence
 If two operators have equal precedence, operations
are performed left to right. i.e.
10 / 5 * 3 = 6
Parentheses are used to override precedence. i.e.
10 / ( 5 * 3)
May 2004
NH-Chapter 2
32
Casting
 Occasionally must convert a value to a different type
to perform certain operations.
 Syntax: (type) expression
10/40 = 0
(double)10/(double)40 = 0.25
10.0/40.0 = 0.25
(int)10.0/(int)40.0 = 0
Cast operators have higher precedence than arithmetic operators.
May 2004
NH-Chapter 2
33
A simple green-yellow-red Traffic signal
 Features:
public TrafficSignal ()
Create a new TrafficSignal, initially green.
public int light ()
The light currently on.
public void change ()
Change to the next light.
May 2004
NH-Chapter 2
34
Traffic signal implementation
 Instance variable: int light
 represent possible lights with integers:
 0 for green, 1 for yellow, 2 for red.
 To isolate client from choice of values for light, use
named class constants
May 2004
NH-Chapter 2
35
Named class constants
public class TrafficSignal {
/**
* The green signal light.
*/
public static final int GREEN = 0;
/**
* The yellow signal light.
*/
public static final int YELLOW = 1;
/**
* The red signal light.
*/
public static final int RED = 2;
…
}
May 2004
NH-Chapter 2
36
Implementing constructor
/**
* Create a new TrafficSignal, initial
*/
public TrafficSignal () {
light = TrafficSignal.GREEN;
}
May 2004
NH-Chapter 2
37
Implementing command change
/**
* Change to the
next light.
*/
public void change
() {
light = (light
+ 1) by
% 33;
Note: remainder
will yield values 0, 1, or 2
}
May 2004
NH-Chapter 2
38
Methods with parameters
 Often client must provide additional data when
invoking a constructor or method.
 Additional data provided are parameters.
May 2004
NH-Chapter 2
39
Methods with parameters
 Example: model a Playing card.
 The constructor needs two parameters:
 suit
 Rank
 As the client must specify which card to create.
May 2004
NH-Chapter 2
40
Constructor with parameters
parameters
public PlayingCard
int rank) {
Parameter
type
May 2004
NH-Chapter 2
(int
suit ,
Parameter
name
41
Invoking constructor with
parameters
Client invokes constructor providing two int values
One for suit
Another for rank
new PlayingCard(4, 3)
 This
invocation
PlayingCard with
will
create
a
 suit: spades
 rank (value of card) : 3
May 2004
NH-Chapter 2
42
Executing constructor with
parameters Method variables
When client invokes constructor,
new PlayingCard(4, 3)
 Two int method variables are created:
 named suit and rank
 initialized with 4, and 3 respectively.
 lifetime of method variables: constructor execution .
 destroyed at completion of execution of constructor.
 Lifetime of object’s instance variables : object lifetime .
May 2004
NH-Chapter 2
43
Implementing PlayingCard constructor
 PlayingCard has two instance variables:
private int suit;
private int rank;
 Initialize them in constructor, using client’s values.
 Client’s values are in method variables: suit, rank
May 2004
NH-Chapter 2
44
Implementing PlayingCard constructor
 The following implementation will not work:
public PlayingCard (int suit, int rank)
suit = suit;
rank = rank;
}
In body of method, names suit and rank
refer to method variables only.
May 2004
NH-Chapter 2
45
Implementing PlayingCard constructor
 The keyword this refers to object being constructed.
 this.suit refers to its instance variable suit
 this.rank refers to its instance variable rank.
public PlayingCard (int suit, int ra
this.suit = suit;
this.rank = rank;
}
May 2004
NH-Chapter 2
46
Java in detail: arithmethic
expressions Simple expressions
 Literals
0
7
23
0.5
2.0
3.14159
2.4e-23
Variable names
It denotes value currently stored in variable.
int i1 = 10;
int i2 = -20;
double d1 = 2.5;
double d2 = 0.5;
//evaluating them produces their values:
i1 
10
i2

-20
d1

2.5
d2

May 2004
NH-Chapter 2
int i3 = 30;
i3
0.5

30
47
Java in detail: arithmethic
expressions Operators
 Expressions can be combined with operators to form more
complicated expressions.
i1 / -3

-3
-7 / 2

-3
i1 % -3
May 2004

1
-7 % 2
NH-Chapter 2

-1
48
Java in detail: arithmethic
expressions Numeric promotion
 Operands for binary and unary operators are automatically
converted to similar values of a different type when necessary.
May 2004
7 / 2.0

7.0 / 2.0

3.5
i1 * 0.5

10 * 0.5

10.0 * 0.5
NH-Chapter 2

49
Java in detail: arithmethic
expressions Precedence
 Operators *, /, and % have higher precedence than binary
operators + and -.
 In an un-parenthesized expression multiplication is done
before addition
Multiply before adding
May 2004
i1 + 10 * 2 
i1 + 20

i1 * 10 + 2
10 / 2 + 1
5 + 6 / 10



- 5 + i1 
(-5) + 10
30
100 + 2 
5 + 1

5 + 0

NH-Chapter 2

102
6
5
5
50
Java in detail: arithmethic
expressions Associativity
 Binary operators are left associative: when
expression contains two operators with equal
precedence, operations are performed left to right.
Left operator before right
i1 / 5 * 2
May 2004

2 * 2 
4
10 - 4 - 3

6 - 3 
3
i1/20 * 2

10/20 * 2

0*2

0
2*i1/20

2*10/20

20/20 
1
20 / i1*2

20 / 10*2

2*2

4
NH-Chapter 2
51
Java in detail: Concatenation
 For operands Strings: binary operator “+” denotes
string concatenation.
string1 + string2
 Evaluates to a String containing characters of
string1 with characters of string2 appended.
"abc" + "def"
May 2004
NH-Chapter 2

"abcdef"
52
Java in detail: Concatenation
 If one operands of “+” is a String and the other isn’t, the nonString operand will be converted to a String, and
concatenation performed.
int i = 23;
"abc" + i
i + " "
"2*i=" + 2*i
2+i+"!"
"!"+2+i
May 2004

"abc23“




NH-Chapter 2
"23 "
"2*i=46"
"25!" ( “+” is left associative!)
"!223"
53
Java in detail: Casting
(type)expression
(double)i1
May 2004

(double)10

(double)i1 / i3

10.0 / 30
(int)d3
(int)d4


2
-2
(double)i1/i3

10.0/30
(double)(i1/i3)

(double)0
NH-Chapter 2
10.0


0.3

0.3
0.0
54
Java in detail: basic organizational
structure
 package: a collection of closely related classes.
 compilation unit: a file containing the definition of
one or more classes of a package.
May 2004
NH-Chapter 2
55
Java in detail: basic organizational
structure
packageA;
package B;
public class A1 {
…
} // end of class A1
public class B1 {
…
} // end of class B1
class A3 {
…
} // end of class A3
class B2 {
…
} // end of class B2
A1.java
B1.java
packageA;
package C;
public class A2 {
…
} // end of class A2
public class C1 {
…
} // end of class C1
A2.java
May 2004
C1.java
NH-Chapter 2
56
Java in detail: referring to classes in a
different package,import statements
 Via import statement, can refer to a class in another package
with by name rather than with its fully qualified name.
 Two formats for an import statement:
import packageName.className;
import packageName.*;
import javax.swing.border.LineBorder;
import javax.swing.border.*;
May 2004
NH-Chapter 2
57
Java in detail: referring to classes in a
different package,import statements
 Instead of writing :
javax.swing.border.LineBorder myBorder;
myBorder = new javax.swing.border.LineBorder(myColor
 Write :
import javax.swing.border.LineBorder;
import javax.swing.border.*;
LineBorder myBorder;
myBorder = new LineBorder(myColor);
May 2004
NH-Chapter 2
58
Java in detail: package java.lang
 The predefined package java.lang contains the
definitions of a number of commonly used classes.
 String is a member of java.lang.
 Do not need to explicitely import this package. Java
does it by default.
May 2004
NH-Chapter 2
59
Summary
 Saw how to specify and implement a simple class
using the programming language Java.
 Two objects are related in a fundamental way when
one object uses the other:
 one object queries and command the other.
 This relation is : client-server relationship.
 The client object queries and commands the server
object.
May 2004
NH-Chapter 2
60
Summary
 Definition of class of which the object is an instance,
consists of two parts:
 Specification: a precise description of object’s features as
seen by a client.
 Implementation: internal mechanisms that enable an object
to behave according to its specification.
May 2004
NH-Chapter 2
61
Summary
 Class specification is made up of:
 method specifications
 constructor specifications.
May 2004
NH-Chapter 2
62
Summary
 Methods define
 the specifications
 the implementation of an object’s features.
 A method that defines a query returns a value of a given type.
 A method that defines a command causes object to change
state when it is invoked.
 Constructors are used to create objects and initialize their
states.
May 2004
NH-Chapter 2
63
Summary
 Implementing a class involves
 writing data descriptions for data stored in class instances,
and
 writing method bodies that define the actions the processor
performs when the methods are invoked.
May 2004
NH-Chapter 2
64
Summary
 An object’s data are stored in instance variables.
 Instance variables are created when object is created.
 Instance variables are part of the object’s
implementation
 An instance variable is created with a variable
declaration:
private variableType variableName;
May 2004
NH-Chapter 2
65
Summary
 A method body is made up of a sequence of
statements that implement the method algorithm.
 Statements describe actions the processor performs
when executing the method.
 When method is invoked, processor executes
statements one after another, in the order in which
they appear in the method body.
May 2004
NH-Chapter 2
66
Summary
 Return statement has the form:
return expression;
 Assignment statement has the form:
variable = expression;
May 2004
NH-Chapter 2
67
Summary
 An expression describes how a value is to be computed.
 Arithmetic expressions, in particular, produce numeric values
when they are evaluated.
 Both return statements and assignment statements include
expressions.
May 2004
NH-Chapter 2
68
Summary
 Parameters in method or constructor: indicate that
client provide information when the method or
constructor is invoked.
 Arguments: values client supplies when invoking
method or constructor.
May 2004
NH-Chapter 2
69
Summary
 Method variables: variables allocated for each
parameter and initialized with the argument provided
by the client.
 Method variables: created when the method is
invoked, and deallocated when execution of method
is complete.
May 2004
NH-Chapter 2
70
Summary
 Packages: groups of class definitions that make up a program.
 Classes defined in same package are related to each other:
instances of these classes can access each other by default.
 If a class is to be visible throughout the entire system, it must
be explicitly labeled as public.
 Class definitions are written in source files.
 Each file can contain definition of at most one public class.
May 2004
NH-Chapter 2
71