Title: Chapter 2: Defining a Simple Class
1Chapter 2 Defining a Simple Class
2Object 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.
3Object Interaction Clients and Servers
- Also, you should be able to
- write the specification of a simple class
- implement a simple class
- invoke an objects 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.
4Clients and Servers
- Recall
- an object has features queries and commands.
- objects cooperate to produce a problem solution.
5Client and Server relationship
query
Piece
Player
currentSquare
white
color
white
color
queen
rank
yes
userControlled
d1
d1
square
client
server
response
command
Piece
Player
white
color
moveTo(c2)
white
color
queen
rank
yes
userControlled
d1
square
client
Piece
white
color
queen
rank
c2
square
6Clients 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.
7Clients 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.
8Server specification and Implementation
- Client need only know servers features and use.
- Object specification (interface) definition of
objects features, as seen by its clients. - The implementation provides the internals that
actually make up the features.
9Example 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
10Defining class Counter in Java
package counters / A simple integer
counter. / public class Counter
Definitions of features goes here.
11Specifying a Method for a query
/ The number of items counted. / public
int currentCount ()
Name of method.
Type of value returned by query.
Method implementation goes here.
12Specifying a Method for a command
/ The number of items counted. / public
void incrementCount ()
Name of method.
Type of value returned by command.
Method implementation goes here.
13Class 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.
14Static diagram of the class Counter
Counter
int
currentCount()
void
incrementCount()
void
reset()
15Invoking queries
- clients reference object to Counter myCounter
- To query myCounter for current value of count
myCounter.currentCount()
server
client
Counter
myCounter
4
int
count
myCounter.currentCount()
public
int
currentCount ()
.
.
4
2. object myCounter performs actions as
1. client invokes the method
prescribed by the method definition.
currentCount of the object myCounter.
16Invoking commands
- clients reference object to Counter myCounter
- To command myCounter to reset,
myCounter.reset()
17Interaction diagrams
- client object interacting with a Counter. object
queries Counter for current count, and then give
Counter command reset.
currentCount()
the object is active
executing the method
currentCount
count
time
reset()
18Implementing 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
19Counter object showing instance variable
Counter
Value of variable at some time
10
Type of variable
int
count
Name of variable
Instance variable
Counter
-
int
count
int
currentCount()
void
incrementCount()
void
reset()
Static diagram of class Counter, showing instance
variable
20Implementing 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.
21Implementing 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
-
22Return 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.
23Implementing simple commandsAssignment statement
- A command modifies state of the object.
- Use an assignment statement
- instructs processor to compute a value and store
it in a variable.
- Processor executes assignment in two steps
- computes the value by the expression on RHS
- stores value in variable on LHS, replacing
previous value.
24Implementing command reset
- want to store 0 in the variable count.
- /
- Reset the count to 0.
- /
- public void reset ()
- count 0
-
25Implementing 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
-
26Implementing constructor
- instance variable count must be set to 0 in the
instance creation.
/ Create a new Counter, with the count
initialized to 0. / public Counter () count
0
27Arithmetic expressions
- Expressions that evaluate to integer and floating
point values. - Can be built by combining literals and variable
names with arithmetic operators - addition
- - subtraction
- multiplication
- / division
- remainder
28Unary operators and -
- assume that i1, is an int variables containing 10
3 ? 3 -3 ? -3 i1 ? 10 - i1 ? -10
29Division operator
- / denotes division when applied to two floating
point operands, but integer quotient when applied
to two integer operands.
2.0/4.0 ? 0.5 2/4 ? 0 5.0/4.0 ?
1.25 5/4 ? 1
30Remainder operator
- Primarily used with integer operands
10 5 ? 0 10 3 ? 1 10 6 ? 4 10 11
? 10
31Mixed type expressionsNumeric 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 ? 5.0
32Operator precedence
- What is the order of evaluation in
5 10 2
- Unary and have higher precedence than binary
operators. - , /, have higher precedence than operators ,-
33Operator 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)
34Casting
- 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.
35A simple green-yellow-red Traffic signal
- public TrafficSignal ()
- Create a new TrafficSignal, initially green.
- public int light ()
- The light currently on.
- public void change ()
- Change to the next light.
36Traffic 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
37Named 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
38Implementing constructor
/ Create a new TrafficSignal, initially
green. / public TrafficSignal () light
TrafficSignal.GREEN
39Implementing command change
/ Change to the next light.
/ public void change () light (light 1)
3
- Note remainder by 3 will yield values 0, 1, or 2
40Methods with parameters
- Often client must provide additional data when
invoking a constructor or method. - Additional data provided are parameters.
41Methods with parameters
- Example model a Playing card.
- The constructor needs two parameters
- suit
- Rank
- As the client must specify which card to create.
42Constructor with parameters
public PlayingCard (int suit , int rank)
Parameter name
Parameter type
43Invoking constructor with parameters
- Client invokes constructor providing two int
values - One for suit
- Another for rank
new PlayingCard(4, 3)
- This invocation will create a PlayingCard with
- suit spades
- rank (value of card) 3
44Executing 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 objects instance variables object
lifetime .
45Implementing PlayingCard constructor
- PlayingCard has two instance variables
- private int suit
- private int rank
- Initialize them in constructor, using clients
values. - Clients values are in method variables suit,
rank
46Implementing 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.
47Implementing 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 rank)
this.suit suit this.rank rank
48Java in detail arithmethic expressions Simple
expressions
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 int i3
30 double d1 2.5 double d2
0.5 //evaluating them produces their
values i1 ? 10 i2 ? -20 i3 ? 30
d1 ? 2.5 d2 ? 0.5
49Java in detail arithmethic expressions Operators
- Expressions can be combined with operators to
form more complicated expressions.
i1 / -3 ? -3 -7 / 2 ? -3 i1 -3 ? 1 -7 2 ? -1
50Java in detail arithmethic expressions Numeric
promotion
- Operands for binary and unary operators are
automatically converted to similar values of a
different type when necessary.
7 / 2.0 ? 7.0 / 2.0 ? 3.5 i1 0.5 ? 10
0.5 ? 10.0 0.5 ? 5.0
51Java 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
i1 10 2 ? i1 20 ? 30
i1 10 2 ? 100 2 ? 102 10 / 2 1 ? 5
1 ? 6 5 6 / 10 ? 5 0 ? 5 - 5 i1 ? (-5)
10 ? 5
52Java 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 ? 2 2 ? 4
10 - 4 - 3 ? 6 - 3 ? 3 i1/20 2 ? 10/20
2 ? 02 ? 0 2i1/20 ? 210/20 ? 20/20 ? 1 20 /
i12 ? 20 / 102 ? 22 ? 4
53Java 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" ? "abcdef"
54Java in detail Concatenation
- If one operands of is a String and the other
isnt, the non-String operand will be converted
to a String, and concatenation performed.
int i 23 "abc" i ? "abc23 i " " ? "23
""2i" 2i ? "2i46"2i"!" ? "25!" (
is left associative!)"!"2i ? "!223"
55Java in detail Casting
(type)expression (double)i1 ? (double)10 ? 10.0 (d
ouble)i1 / i3 ? 10.0 / 30 ? 0.333 (int)d3 ? 2(
int)d4 ? -2 (double)i1/i3 ? 10.0/30 ? 0.333 (do
uble)(i1/i3) ? (double)0 ? 0.0
56Java 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.
57Java in detail basic organizational structure
58Java 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.LineBorde
r import javax.swing.border.
59Java in detail referring to classes in a
different package,import statements
javax.swing.border.LineBorder myBorder myBorder
new javax.swing.border.LineBorder(myColor)
import javax.swing.border.LineBorder import
javax.swing.border. LineBorder
myBorder myBorder new LineBorder(myColor)
60Java 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.
61Summary
- 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.
62Summary
- Definition of class of which the object is an
instance, consists of two parts - Specification a precise description of objects
features as seen by a client. - Implementation internal mechanisms that enable
an object to behave according to its
specification.
63Summary
- Class specification is made up of
- method specifications
- constructor specifications.
64Summary
- Methods define
- the specifications
- the implementation of an objects 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.
65Summary
- 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.
66Summary
- An objects data are stored in instance
variables. - Instance variables are created when object is
created. - Instance variables are part of the objects
implementation - An instance variable is created with a variable
declaration
private variableType variableName
67Summary
- 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.
68Summary
- Return statement has the form
return expression
- Assignment statement has the form
variable expression
69Summary
- 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.
70Summary
- 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.
71Summary
- 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.
72Summary
- 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.