Download as pdf or txt
Download as pdf or txt
You are on page 1of 691

S.C.

Cheung
HKUST
CSIT5100
Object-Oriented Software
Development of Enterprise Systems
!o is t!is co"rse for#
If you can answer yes to:

Have you done some OO programmng!

"o you want to refresh OO concepts n #ava!

"o you want to have hands$on practce on %u&dng


automatc tester to fnd %ugs under 'c&pse!

"o you want to &earn some systematc techn(ues


n testng your code!

"o you want to )now how to start desgnng an


enterprse OO system!
CSIT*+,, - scc
!at do yo" need for t!is co"rse#
CSIT*+,,, . scc
If yo" want to master somet!in$ %
CSIT*+,, / scc
practce t0
S.C. Cheung
HKUST
CSIT5100
Overview on Object-Oriented
Concepts
CSIT*+,, 1 scc
Object-Oriented &otation - '()

a genera& purpose vsua& mode&ng &anguage


for systems

ncorporates current %est practce n mode&ng


techn(ues and software engneerng

software deve&opment methodo&ogy neutra&

ndustry standard OO mode&ng &anguage 2%ut


can a&so %e used for non$OO systems3

%asc premse: software systems can %e


mode&ed as co&&ectons of co&&a%oratng
o%4ects
CSIT*+,, 5 scc
Objects# !at are t!ey#
CSIT*+,, 6 scc
!y Objects#

To more accurate&y ref&ect rea&ty n a


mode&

To reduce the semantc gap %etween


rea&ty and a mode&

To &oca&7e changes to the mode&


We can model reality as a number
of interacting objects
CSIT*+,, 8 scc
Concept"al (odel * Implementation
conceptual
9 do not consder any aspects of mp&ementaton of o%4ects
Focus on identifying the objects in the problem domain
implementation
9 consder a&& deta&s of o%4ects 2e:terna& and nterna&3
Focus on how to code objects
Modeling proceeds from the conceptual to
implementation
Same OO concepts at all levels
CSIT*+,, +, scc
- wings,
+,ST-+CTIO&
mental process of selecting some characteristics and
properties and excluding others that are not relevant
mental process of selecting some characteristics and
properties and excluding others that are not relevant
landing gear, ...

G
abstraction is always for some purpose
G
many different abstractions of the same thing are possible
G
all abstractions are incomplete descriptions of reality
We do not need completeness, just modeling adequacy!
flies,
CSIT*+,, ++ scc
+3 roads.
-3 &and topo&ogy 2e.g.; contours showng e&evaton
a%ove sea &eve&.
.3 hstorca& stes to see 2e.g.; the HKUST %each3.
/3 the types and p&aces of vegetaton 2.e.; trees
and other types of p&ants3.
*3 &ocaton of h)ng tra&s.
13 %us routes.
If you had to draw a map of the area around HKUST to e:p&an to
someone how to get to HKUST from Cho Hung; what s the one most
mportant thng you wou&d nc&ude!
.'ESTIO&#
CSIT*+,, +- scc
+3 roads.
-3 &and topo&ogy 2e.g.; contours showng
e&evaton a%ove sea &eve&.
.3 hstorca& stes to see 2e.g.; the HKUST
%each3.
/3 the types and p&aces of vegetaton 2.e.;
trees and other types of p&ants3.
*3 &ocaton of h)ng tra&s.
13 %us routes.
If you had to draw a map of the area around HKUST to e:p&an to someone
how hgh the <cademc =u&dng s a%ove sea &eve&; what s the one most
mportant thng you wou&d nc&ude!
.'ESTIO&#
CSIT*+,, +. scc
+,ST-+CTIO&S

classification > group sm&ar nstances of o%4ects


DBMS
software
Sybase . . . Access Oracle
IS_MEMBER_OF
relationship
pick out common properties and ignore unique properties
Microsoft
software
Word PowerPoint . . .
IS_MEMBER_OF
relationship
CSIT*+,, +/ scc
T/0ES O1 +,ST-+CTIO&S 2cont3d4

aggregation > group dssm&ar sets of o%4ects


airplane
fuselage . . . wing landing gear
IS_PART_OF
relationship
ignore differences among the parts and concentrate
on the fact that they form the whole
CSIT*+,, +* scc
T/0ES O1 +,ST-+CTIO&S 2cont3d4

generaliation > group sm&ar sets of o%4ects


student
postgrad . . . secondary undergrad
IS_A
relationship
note difference between classification and generaliation
9 c&assfcaton 9 app&ed to ndvdua& nstances of o%4ects
9 genera&7aton 9 app&ed to sets of o%4ects 2c&asses3
superclass/supertype
subclass/subtype
CSIT*+,, +1 scc
T/0ES O1 +,ST-+CTIO&S 2cont3d4
student
undergrad
John . . . Sam Tina
. . . name student id
generalization generalization
aggregation aggregation
classification classification
?ote: we can com%ne dfferent types of a%stracton when mode&ng
CSIT*+,, +5 scc
file
directory
.'ESTIO&#
Consder the re&atonshp %etween f&es and drectores n a computer
system. @hch type2s3 of a%stracton mode&s ths re&atonshp!
+3 c&assfcaton on&y
-3 aggregaton on&y
.3 genera&7aton on&y
/3 c&assfcaton and aggregaton
*3 aggregaton and genera&7aton
13 c&assfcaton and genera&7aton
53 c&assfcaton; aggregaton and genera&7aton
63 none of the a%ove
CSIT*+,, +6 scc
O,5ECT
interface describes the operations
which an object can perform
sccs Savings
Account
(a real-life object)
a concept, abstraction or thing with crisp boundaries
and meaning which plays a role with respect to a
request for an operation
a concept, abstraction or thing with crisp boundaries
and meaning which plays a role with respect to a
request for an operation
getBalance
deposit
withdraw
CSIT*+,, +8 scc
getBalance
deposit
withdraw
O,5ECT 6 0-O0E-TIES
sccs Savings
Account
account number (integer value)
balance (money value)
state
getBalance
getBalance method (code)
deposit
deposit method (code)
withdraw
withdraw method (code)
payInterest
payInterest method (code)
behavior
identity
CSIT*+,, -+ scc
2O,5ECT4 C)+SS
a description of a group of objects that have common!
9 state - relationships
9 behavior - semantics
a description of a group of objects that have common!
9 state - relationships
9 behavior - semantics
G
provides a template to create objects (a factory for objects)
a class is a classifier; an object is an instance
Why classes?

conveniently describes a collection of objects abstraction

specify what values are acceptable in a given context


Choosing appropriate classes is an important design decision
How are classes and modules related?

classes can be thought of as loosely coupled, highly cohesive modules


CSIT*+,, -- scc
.'ESTIO&#

app&y c&assfcaton a%stracton to o%4ects to form c&asses


IS_MEMBER_OF
relationship
@hch type of a%stracton re&ates o%4ects and c&asses!
+3 c&assfcaton on&y
-3 aggregaton on&y
.3 genera&7aton on&y
/3 c&assfcaton and aggregaton
*3 aggregaton and genera&7aton
13 c&assfcaton and genera&7aton
53 c&assfcaton; aggregaton and genera&7aton
63 none of the a%ove 2ths s not a type of
a%stracton3
CSIT*+,, -. scc
C)+SS 6 +TT-I,'TE

each attr%ute has a:


9 name 2un(ue wthn a c&ass; %ut not across c&asses3
a description of data values held by objects in a class
a description of data values held by objects in a class
9 type 2specfes the doman of va&ues from whch an attr%ute can
ta)e ts va&ues3

contnuous 2e.g.; sa&ary3 dscrete 2e.g.; age3


9 vs%&ty: pu%&c 2A3; prvate 2$3; protected 2B3; pac)age 2C3
9 nta& va&ue 2optona&3
9 mu&tp&cty 2optona&D num%er of smu&taneous va&ues; e.g.;
te&ephone num%erD defau&t s e:act&y +3
9 changea%&ty: fro7en; addOn&y; no constrant 2defau&t3

%ase attr%ute versus derved attr%ute


9 e.g.; %rthdate versus age
CSIT*+,, -/ scc
+TT-I,'TES 6 '() &OT+TIO&
EEstereotypeFF vs%&ty name Gmu&tp&ctyH: type':presson I nta&Ja&ue
KpropertyStrngL
propertyStrng $F a comma separated &st of propertes or constrants
On&y name s mandatory
"xamples
A s7e: <rea I 2+,,;,,,3 Kfro7enL
name: strng
te&ephoneG,..-H: strng
te&ephoneG+; .../H: strng
$ sa&ary: Money KF,; E+;,,,;,,,L
#ou are not required to memorie this syntax$
CSIT*+,, -* scc
."estion#

app&y aggregaton a%stracton to attr%utes to form c&asses


name instructor prerequisite course#
IS_PART_OF
relationship
Course
@hch type of a%stracton re&ates attr%utes and
c&asses!
+3 c&assfcaton on&y
-3 aggregaton on&y
.3 genera&7aton on&y
/3 c&assfcaton and aggregaton
*3 aggregaton and genera&7aton
13 c&assfcaton and genera&7aton
53 c&assfcaton; aggregaton and genera&7aton
63 none of the a%ove 2ths s not a type of
a%stracton3
CSIT*+,, -1 scc
C)+SS 6 O0E-+TIO&
Company hre; fre; pay$dvdends; N
Course regster; wave$prere(uste; N

nvo)ed %y a message sent to an o%4ect

operaton sgnature: name of operaton 2ca&&ed selector3; num%er and


types of the arguments; and type of the resu&t va&ue

vs%&ty: pu%&c 2A3; prvate 2$3; protected 2B3; pac)age 2C3

sde effects: f the e:ecuton of an operaton changes the state of an


o%4ect 2(uery operaton no sde effects3
a function or transformation that may be applied to
or by objects in a class
a function or transformation that may be applied to
or by objects in a class
CSIT*+,, -5 scc
C)+SS 6 (ET7OD

po&ymorphc operaton 9 an operaton that can have severa&


dfferent methods
c&ass operaton
File print
%S&'' file %S&'' file print method
digitied file digitied file print method
the implementation of an operation for a class
the implementation of an operation for a class

dynamc %ndng 9 choosng the method to e:ecute for an


operaton %ased on the o%4ectOs c&ass
(ow does a requesting object know whether the returned value
is the result of accessing an attribute value or of a calculation
performed by a method)
CSIT*+,, -6 scc
SCO0E

attr%utes and operatons norma&&y have nstance scope


2.e.; they app&y toPoperate on a sng&e o%4ect nstance3

sometmes; t s usefu& to have attr%utes and operatons


that c&ass scope 2.e.; they app&y toPoperate on an entre
c&ass of o%4ects3

attr%utes whose va&ues are c&ass determned 9 a counter

o%4ect constructors 9 create new o%4ect nstances


G
n UMQ notaton; such attr%utesPoperatons are
under&ned
CSIT*+,, -8 scc
C)+SS 6 '() 8-+07IC+) &OT+TIO&
Account
-accoutNumber : int
+amount : money
-count : int = 0
+create(aNumber : int)
-incrementCount( )
+getCount( ) : int
+getNumber( ) : int
+balance( ) : money
+deposit(amount)
+withdraw(amount)
-payInterest( )
Visibility
+ public
- private
# protected
~ package
Class name
attribute
compartment
operation
compartment
extra
compartment
&heung!
Savngs<ccount
&heung!
Savngs<ccount
CSIT*+,, ., scc
a re&atonshp %etween a c&ass and one or more refned versons
a re&atonshp %etween a c&ass and one or more refned versons
8E&E-+)I9+TIO&
Vehicle
Van Car Truck
Compact Midsize Full-size
car-size
discriminator
vehicle-type
generalization generalization
specialization specialization
discriminator: an attr%ute of enumeraton type that ndcates whch property of a c&ass s %eng
a%stracted %y a genera&7aton
subclass
superclass
superclass
subclass
CSIT*+,, .+ scc
8E&E-+)I9+TIO& 6
I&7E-IT+&CE

e:tract sm&artes 2common attr%utes and operatons3;


put them n a superc&ass and nhert them to
su%c&ass2es3

reduces redundancy of descrptons

promotes reusa%&ty of descrptons


only define properties and behaviour in one place
allows substitution of an object of a superclass
with an object of the subclass
the assumption of properties by a
subclass from its superclasses
the assumption of properties by a
subclass from its superclasses
&heung!
Interest<ccount
&heung!
Interest<ccount
CSIT*+,, .- scc
8E&E-+)I9+TIO& 6 +,ST-+CT C)+SS

used for mode&ng purposes as a contaner for defntons; %ut no


nstances of the c&ass are of nterest
Checking Savings
Account
?ote: Operatons may a&so %e a%stract no method specfed
Shown n UMQ %y usng ta&cs
a class that has no direct instances
a class that has no direct instances
."i:
CSIT*+,,, .. scc
-elatin$ t!em to Des;top Comp"ter#
CSIT*+,,, ./ scc
-elatin$ < i0ad Devices to i0ad#
CSIT*+,, .* scc
CSIT*+,, .1 scc
Re&atng the concept of
Sad to the concept of
Computer!
CSIT*+,, .5 scc
Re&atng the concept of
"es)top Computer to the
concept of Computer!
0ractice in 5ava
CSIT*+,, .6 scc
Scture
GeometricObject
Rectang&e
Crc&e Trang&e
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 1
Introduction to Computers,
Programs, and Java
(Self Study Materials)
Liang, Introduction to Java Programming
Objectives
!
To review computer basics, programs, and
operating systems (1.!1."#.
!
To represent numbers in binary, decima$, and
%e&adecima$ (1.'#.
!
To understand t%e re$ations%ip between Java and
t%e (or$d (ide (eb (1.)#.
!
To distinguis% t%e terms *PI, I+,, and J+- (1..#.
!
To write a simp$e Java program (1./#.
!
To disp$ay output on t%e conso$e (1./#.
!
To create, compi$e, and run Java programs (1.0#.
!
To 1now t%e basic synta& o2 a Java program
(1.13#.
!
(45I# To disp$ay output in a dia$og bo& (1.11#.
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 3
(%y Java6
The answer is that Java enables users to develop and
deploy appliations on the !nternet for servers" des#top
o$puters" and s$all hand%held devies.
!
Java is a general purpose progra$$ing language.
!
!t an be used to progra$&
!
'nterprise syste$s (Struts" Spring fra$ewor#" J('')
!
!nternet appliations (Applets" JS)" Servlets" Java*eans)
!
Mobile appliations (Android apps)
Liang, Introduction to Java Programming
Adapted by S.C. Cheung +
TicTacToe 7tanda$one
Liang, Introduction to Java Programming
Adapted by S.C. Cheung ,
TicTacToe *pp$et
Liang, Introduction to Java Programming
Adapted by S.C. Cheung -
Java8s 9istory
!
James 4os$ing and 7un :icrosystems
!
Oa1
!
Java, :ay 3, 100', 7un (or$d
!
9otJava
;
T%e <rst Java!enab$ed (eb browser
!
,ar$y 9istory (ebsite=
http&../ava.sun.o$.features.1001.2,.birthday.ht$l
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 3
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is *rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
4ptional
www.s.ar$strong.edu.liang.intro3e.JavaCharateristis.pdf
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 1
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Java is partially $odeled on C55" but greatly
si$plified and i$proved. So$e people refer to
Java as 6C55%%6 beause it is li#e C55 but
with $ore funtionality and fewer negative
aspets.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 0
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Java is inherently ob/et%oriented.
Although $any ob/et%oriented languages
began stritly as proedural languages"
Java was designed fro$ the start to be
ob/et%oriented. 4b/et%oriented
progra$$ing (44)) is a popular
progra$$ing approah that is replaing
traditional proedural progra$$ing
tehni7ues.
4ne of the entral issues in software
develop$ent is how to reuse ode.
4b/et%oriented progra$$ing provides
great fle8ibility" $odularity" larity" and
reusability through enapsulation"
inheritane" and poly$orphis$.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 12
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
9istributed o$puting involves several
o$puters wor#ing together on a networ#.
Java is designed to $a#e distributed
o$puting easy. Sine networ#ing
apability is inherently integrated into
Java" writing networ# progra$s is li#e
sending and reeiving data to and fro$ a
file.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 11
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
:ou need an interpreter to run Java
progra$s. The progra$s are o$piled into
the Java ;irtual Mahine ode alled
byteode. The byteode is
$ahine%independent and an run on any
$ahine that has a Java interpreter" whih
is part of the Java ;irtual Mahine (J;M).
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 1(
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Java o$pilers an detet $any proble$s
that would first show up at e8eution ti$e
in other languages.
Java has eli$inated ertain types of
error%prone progra$$ing onstruts found
in other languages.
Java has a runti$e e8eption%handling
feature to provide progra$$ing support
for robustness.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 13
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Java i$ple$ents several seurity
$ehanis$s to protet your syste$ against
har$ aused by stray progra$s.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 1+
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
(rite once, run anyw%ere
(it% a Java Airtua$ :ac%ine (JA:#,
you can write one program t%at
wi$$ run on any p$at2orm.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 1,
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Because Java is arc%itecture
neutra$, Java programs are
portab$e. T%ey can be run on any
p$at2orm wit%out being
recompi$ed.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 1-
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Java runs slightly slower than C55
4ptional
Extracted from: C++ vs. Java 1.6 - A fair benchmark
http&..www.irrliht3d.org.pivot.entry.php<id=++-
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 13
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
:u$tit%read programming is smoot%$y
integrated in Java, w%ereas in ot%er
$anguages you %ave to ca$$
procedures speci<c to t%e operating
system to enab$e mu$tit%reading.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 11
C%aracteristics o2 Java
!
Java Is 7imp$e
!
Java Is Object!Oriented
!
Java Is +istributed
!
Java Is Interpreted
!
Java Is >obust
!
Java Is 7ecure
!
Java Is
*rc%itecture!?eutra$
!
Java Is Portab$e
!
Java@s Per2ormance
!
Java Is :u$tit%readed
!
Java Is +ynamic
Java was designed to adapt to an
evo$ving environment. ?ew code can be
$oaded on t%e Cy wit%out recompi$ation.
T%ere is no need 2or deve$opers to create,
and 2or users to insta$$, major new
so2tware versions. ?ew 2eatures can be
incorporated transparent$y as needed.
4ptional
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 10
J+- Aersions
!
J+- 1.3 (100'#
!
J+- 1.1 (100)#
!
J+- 1. (100/# a.1.a. J+- or Java
!
J+- 1.D (333#
!
J+- 1." (33#
!
J+- 1.' (33"# a.1.a. J+- ' or Java '
!
J+- 1.) (33)# a.1.a. J+- ) or Java )
!
JDK 1.7 (May 2011) a.k.a. JDK 7 or Java 7
!
(e use Java . in t%is course, and mention t%e
new 2eatures in Java . w%erever appropriate.
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (2
J+- ,ditions
!
Java 7tandard ,dition (J7,#
;
J7, can be used to deve$op c$ient!side standa$one
app$ications or app$ets.
!
Java ,nterprise ,dition (J,,#
;
J,, can be used to deve$op server!side
app$ications suc% as Java serv$ets and Java
7erverPages.
!
Java :icro ,dition (J:,#.
;
J:, can be used to deve$op app$ications 2or
mobi$e devices suc% as ce$$ p%ones.
T%is course uses J7, to introduce Java
programming.
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (1
Java I+, Too$s
!
Bor$and JBui$der
!
?etBeans Open 7ource by 7un
!
7un O?, 7tudio by 7un :icro7ystems
!
Eclipse Open Source by IM
;
!lassic version
Liang, Introduction to Java Programming
Adapted by S.C. Cheung ((
* 7imp$e Java Program
Edit: Welcome.java
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
Systemoutprintln(!Welcome to Java!!)"
#
#
Compi$e= javac (e$come.java
(e$come.c$ass
>un= java (e$come
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (3
,diting 5sing ?otePad
To use NotePad, type
notepad Welcome.java
from the DOS prompt.
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (+
,diting 5sing (ordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (,
9ow does Java wor16
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (-
(%at do you need to do6

Soure Code
Create.Modify Soure Code
Co$pile Soure Code
i.e." /ava >elo$e./ava
*yteode
?un *yteode
i.e." /ava >elo$e
?esult
!f o$pilation errors
!f runti$e errors or inorret result
publi lass >elo$e @
publi stati void $ain(StringAB args) @
Syste$.out.println(6>elo$e to JavaC6)D
}
}
E
Method >elo$e()
2 aloadF2
E

Method void $ain(/ava.lang.StringAB)
2 getstati G( E
3 ld G3 HString ">elo$e to
JavaC"I
, invo#evirtual G+ E
1 return

Saved on the dis#
stored on the dis#
Soure ode (developed by the progra$$er)
*yte ode (generated by the o$piler for J;M
to read and interpret" not for you to understand)
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (3
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
Systemoutprintln(!Welcome to Java!!)"
#
#
Trace a Program ,&ecution
'nter $ain $ethod
animation
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (1
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
Systemoutprintln(!Welcome to Java!!)"
#
#
Trace a Program ,&ecution
'8eute state$ent
animation
Liang, Introduction to Java Programming
Adapted by S.C. Cheung (0
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
Systemoutprintln(!Welcome to Java!!)"
#
#
Trace a Program ,&ecution
animation
print a $essage to the
onsole
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 32
5se2u$ On$ine 7upp$ements
(%ttp=EEwww.cs.armstrong.eduE$iangEintro/eEsupp$ement.%tm$#
!
7upp$ement I!B 2or insta$$ing and
con<guring J+-
!
7upp$ement I!C 2or compi$ing and running
Java 2rom t%e command window 2or detai$s
!
7upp$ement I!+ 2or coding sty$e convention
(FimportantF#
!
7upp$ement II!+G, 2or deve$oping Java
programs on ,c$ipse (FimportantF#
!
7upp$ement III!H 2or testing c$asses using
Junit (FimportantF#
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 31
Compi$ing and >unning
Java 2rom ,c$ipse
!
7upp$ement II!+G,
Liang, Introduction to Java Programming
9ow is t%e code
structured6
(%at goes in a source
<$e (e.g.,
Iactoria$.java#6
c$ass
Adapted by S.C. Cheung 3(
publicclassIactoria$ K
publics#a#icin#2actoria$(in
#n#K
i$(nLM1#re#urn1N
re#urn2actoria$(n!1#FnN
O

publics#a#icvoi%main(7trin
gargsPQ#K

7ystem.out.print$n(2actoria$("
##N
O
O
Liang, Introduction to Java Programming
9ow is t%e code
structured6
(%at goes in a c$ass6
met%ods
Adapted by S.C. Cheung 33
publicclassIactoria$ K
publics#a#icin#2actoria$(in
#n#K
i$(nLM1#re#urn1N
re#urn2actoria$(n!1#FnN
O

publics#a#icvoi%main(7trin
gargsPQ#K

7ystem.out.print$n(2actoria$("
##N
O
O
Liang, Introduction to Java Programming
9ow is t%e code
structured6
(%at goes in a
met%od6
statements
Adapted by S.C. Cheung 3+
publicclassIactoria$ K
publics#a#icin#2actoria$(in
#n#K
i$(nLM1#re#urn1N
re#urn2actoria$(n!1#FnN
O

publics#a#icvoi%main(7trin
gargsPQ#K

7ystem.out.print$n(2actoria$("
##N
O
O
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 3,
Iurt%er *natomy
!
Comments
!
Pac1age
!
>eserved words
!
T%e main met%od
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 3-
Comments
In Java, comments are preceded by=
!
two s$as%es (EE# in a $ine, or
!
enc$osed between EF and FE in one or
mu$tip$e $ines.
(%en t%e compi$er sees EE, it ignores a$$ te&t
a2ter EE in t%e same $ine.
(%en it sees EF, it scans 2or t%e ne&t FE and
ignores any te&t between EF and FE.
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 33
Pac1age
T%e <rst $ine in t%e program (pac1age introN#
speci<es a pac1age name, intro, 2or t%e c$ass
/$
$ %actorial&ava
$/
package intro"
public class %actorial
{
public static int 'actorial( int n ) {
if ( n ()* ) return *"
return 'actorial( n+* ) $ n"
#
public static void main(String args[]){
Systemoutprintln ( 'actorial ( , ) )"
#
#
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 31
main :et%od
T%e main met%od provides t%e contro$ o2
program Cow. Java virtua$ mac%ine starts
e&ecuting a program 2rom its main met%od.

T%e main met%od $oo1s $i1e t%is=

pub$ic static void main(7tringP Q args# K


EE 7tatementsN
O
Liang, Introduction to Java Programming
Adapted by S.C. Cheung 30
+isp$aying Te&t in a
:essage +ia$og Bo&
Hou can use t%e s%ow:essage+ia$og
met%od in t%e JOptionPane c$ass.
JOptionPane is one o2 t%e many
prede<ned c$asses in t%e Java system,
w%ic% can be reused rat%er t%an
Rreinventing t%e w%ee$.S
Liang, Introduction to Java Programming
Adapted by S.C. Cheung +2
T%e s%ow:essage+ia$og
:et%od
JOptionPane.s%ow:essage+ia$og(nu$$,
T(e$come to JavaUT,
R+isp$ay :essageT,
JOptionPane.I?IO>:*TIO?V:,77*4,##N
Liang, Introduction to Java Programming
Adapted by S.C. Cheung +1
Two (ays to Invo1e t%e
:et%od
T%ere are mu$tip$e ways to use t%e
s%ow:essage+ia$og met%od. Ior t%e time being, a$$
you need to 1now are two ways to invo1e it.
One is to use a statement as s%own in t%e e&amp$e=
JOptionPane.s%ow:essage+ia$og(nu$$, &,
y, JOptionPane.I?IO>:*TIO?V:,77*4,##N
w%ere & is a string 2or t%e te&t to be disp$ayed, and y is
a string 2or t%e tit$e o2 t%e message dia$og bo&.
T%e ot%er is to use a statement $i1e t%is=
JOptionPane.s%ow:essage+ia$og(nu$$, &#N
w%ere & is a string 2or t%e te&t to be disp$ayed.
Liang, Introduction to Java Programming
>esources
!
Hou may <nd t%e source code o2 e&amp$es in
t%e notes at=
;
%ttp=EEwww.cs.armstrong.eduE$iangEintro/eEe&amp$eso
urce.%tm$
!
On$ine supp$ement sites
; %ttp=EEwww.cs.armstrong.eduE$iangEintro/eE
; %ttp=EEwww.opente&tboo1.orgE33/E3.E3.Eintroductio
n!to!programming!using!javaE
;
%ttp=EEdown$oad.orac$e.comEjavaseEtutoria$E
;
%ttp=EEwww.javabeginner.comE
; %ttp=EEwww.$earn!java!tutoria$.comE
Adapted by S.C. Cheung +(
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1
Objects and Classes
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2
Motivation
!
Create two TV objects with
different properties.
TestTV
TestTV
TV
TV
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3
Objectives
!
To describe objects and classes, and use classes to model objects
(7.2).
!
To use U! "raphical notations to describe classes and objects
(7.2).
!
To declare a class and create an object from a class (7.#).
!
To construct objects usin" constructors (7.#).
!
To distin"uish between object reference $ariables and primiti$e
data t%pe $ariables (7.&).
!
To use classes 'ate, (andom, and )*rame in the )a$a librar%
(7.+).
!
To distin"uish between instance and static $ariables and methods
(7.,).
!
To declare pri$ate data fields with appropriate "et and set
methods (7.7).
!
To encapsulate data fields to ma-e classes eas% to maintain
(7..).
!
To differentiate between primiti$e/t%pe ar"uments and object/t%pe
ar"uments (7.0).
!
To de$elop methods with object ar"uments (7.0).
!
To store and process objects in arra%s (7.12).
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
4
OO Programming Concepts
Object-oriented programming (OOP) involves
programming using objects. An object represents
an entit in t!e real "orld t!at can be distinctl
identi#ied. $or e%ample& a student& a des'& a circle&
a button& and even a loan can all be vie"ed as
objects. An object !as a uni(ue identit& state& and
be!aviors. )!e state o# an object consists o# a set o#
data fields (also 'no"n as properties) "it! t!eir
current values. )!e behavior o# an object is de#ined
b a set o# met!ods.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*
Objects
An object !as bot! a state and be!avior. )!e state
de#ines t!e object& and t!e be!avior de#ines "!at
t!e object does.

Class +ame, Circle

-ata $ields,
radius is .......

/et!ods,
getArea

Circle Object 1

-ata $ields,
radius is 10

Circle Object 2

-ata $ields,
radius is 2*


Circle Object 3

-ata $ields,
radius is 12*


A class template


)!ree objects o#
t!e Circle class
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1
Classes
Classes are constructs t!at de#ine objects o# t!e
same tpe. A 2ava class uses variables to de#ine
data #ields and met!ods to de#ine be!aviors.
Additionall& a class provides a special tpe o#
met!ods& 'no"n as constructors& "!ic! are
invo'ed to construct objects #rom t!e class.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3
Classes

class Circle {
/** The radius of this circle */
double radius = 1.0;

/** Construct a circle object */
Circle() {
}

/** Construct a circle object */
Circle(double newadius) {
radius = newadius;
}

/** eturn the area of this circle */

double !et"rea() {
return radius * radius * #.1$1%&;
}
}

'ata field

(ethod

Constructors

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
4
5/6 Class -iagram

Circle

radius, double

Circle()
Circle(ne"7adius, double)
getArea(), double
circle1, Circle

radius, 10

Class name


-ata #ields


Constructors and
/et!ods


circle2, Circle

radius, 2*

circle3, Circle

radius, 12*

5/6 Class -iagram


5/6 notation
#or objects


Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
8
Example: Defning Classes
and Creating Objects
!
3bjecti$e4 'emonstrate
creatin" objects, accessin"
data, and usin" methods.
TestCircle1
TestCircle1
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
10
Constructors
Circle() 5
6
Circle(double new(adius) 5
radius 7 new(adius8
6
Constructors are a special
'ind o# met!ods t!at are
invo'ed to construct objects.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
11
Constructors& cont.
A constructor "it! no parameters is re#erred to as a
no-arg constructor.
9 Constructors must !ave t!e same name as t!e
class itsel#.
9 Constructors do not !ave a return tpe:not even
void.
9 Constructors are invo'ed using t!e ne" operator
"!en an object is created. Constructors pla t!e
role o# initiali;ing objects.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
12
Creating Objects 5sing
Constructors
new Class9ame()8
:;ample4
new Circle()8
new Circle(+.2)8
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
13
-e#ault Constructor
A class ma be declared "it!out constructors. <n
t!is case& a no-arg constructor "it! an empt bod
is implicitl declared in t!e class. )!is constructor&
called a default constructor& is provided
automaticall only if no constructors are explicitly
declared in the class.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
14
-eclaring Object 7e#erence =ariables
To reference an object, assi"n the
object to a reference $ariable.
To declare a reference $ariable, use
the s%nta;4
Class9ame object(efVar8
:;ample4
Circle m%Circle8
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1*
-eclaring>Creating Objects
in a ?ingle ?tep
Class9ame object(efVar 7 new Class9ame()8
:;ample4
Circle m%Circle 7 new Circle()8
Create an object
Assign object re#erence
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
11
Accessing Objects
!
(eferencin" the object<s data4
object(efVar.data
e.g., m%Circle.radius
!
=n$o-in" the object<s method4

object(efVar.method9ame(ar"uments)
e.g., m%Circle."et>rea()
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
13
)race Code
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A
-eclare mCircle
no value mCircle
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
14
)race Code& cont.
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A

, Circle

radius, *.0

no value mCircle
Create a circle
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
18
)race Code& cont.
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A

, Circle

radius, *.0

re#erence value mCircle
Assign object
re#erence to mCircle
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
20
)race Code& cont.
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A

, Circle

radius, *.0

re#erence value mCircle
no value ourCircle
-eclare ourCircle
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
21
)race Code& cont.
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A

, Circle

radius, *.0

re#erence value mCircle
no value ourCircle

, Circle

radius, 1.0

Create a ne"
Circle object
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
22
)race Code& cont.
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A

, Circle

radius, *.0

re#erence value mCircle
re#erence value ourCircle

, Circle

radius, 1.0

Assign object
re#erence to ourCircle
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
23
)race Code& cont.
Circle mCircle @ ne" Circle(*.0)A
Circle ourCircle @ ne" Circle()A
ourCircle.radius @ 100A

, Circle

radius, *.0

re#erence value mCircle
re#erence value ourCircle

, Circle

radius, 100.0

C!ange radius in
ourCircle
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
24
Caution
(ecall that %ou use
ath.method9ame(ar"uments) (e."., ath.pow(#, 2.+))
to in$o-e a method in the ath class. Can %ou
in$o-e "et>rea() usin" Circle1."et>rea()? The
answer is no. >ll the methods used before this
chapter are static methods, which are defined usin"
the static -e%word. @owe$er, "et>rea() is
non/static. =t must be in$o-ed from an object usin"
object(efVar.method9ame(ar"uments) (e.".,
m%Circle."et>rea()).
ore e;planations will be "i$en in Aection 7.,,
BAtatic Variables, Constants, and ethods.C
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2*
7e#erence -ata $ields
The data fields can be of reference t%pes. *or
e;ample, the followin" Atudent class contains
a data field name of the Atrin" t%pe.
)ublic class *tudent {
*trin! na+e; // na+e has default ,alue null
int a!e; // a!e has default ,alue 0
boolean is*cience(ajor; // is*cience(ajor has default ,alue false
char !ender; // c has default ,alue -.u0000-
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
21
)!e null =alue
=f a data field of a reference
t%pe does not reference an%
object, the data field holds a
special literal $alue, null.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
23
-e#ault =alue #or a -ata $ield
The default $alue of a data field is null
for a reference t%pe, 2 for a numeric
t%pe, false for a boolean t%pe, and
DEu2222D for a char t%pe. @owe$er, )a$a
assi"ns no default $alue to a local
$ariable inside a method.
)ublic class Test {
)ublic static ,oid +ain(*trin!/0 ar!s) {
*tudent student = new *tudent();
*1ste+.out.)rintln(2na+e3 2 4 student.na+e);
*1ste+.out.)rintln(2a!e3 2 4 student.a!e);
*1ste+.out.)rintln(2is*cience(ajor3 2 4 student.is*cience(ajor);
*1ste+.out.)rintln(2!ender3 2 4 student.!ender);
}
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
24
B%ample
public class Test 5
public static $oid main(Atrin"FG ar"s) 5
int ;8 HH ; has no default $alue
Atrin" %8 HH % has no default $alue
A%stem.out.println(I; is I J ;)8
A%stem.out.println(I% is I J %)8
6
6
Compilation error, variables not
initiali;ed
2ava assigns no de#ault value to a local variable inside a met!od.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
28
-i##erences bet"een =ariables o#
Primitive -ata )pes and Object )pes

1 Primitive tpe int i @ 1 i
Object tpe Circle c c re#erence
Created using ne" Circle()

c, Circle

radius @ 1
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
30
Coping =ariables o# Primitive
-ata )pes and Object )pes

i


Primitive tpe assignment i @ j


Ce#ore,


1


j

2

i


A#ter,


2


j

2


c1


Object tpe assignment c1 @ c2


Ce#ore,





c2





c1


A#ter,


c2


c1, Circle
radius @ *

C2, Circle
radius @ 8







c1, Circle
radius @ *

C2, Circle
radius @ 8

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
31
Darbage Collection
>fter e;ecutin" c1 7 c2, c1 and c2
reference the same object.
E
The Circle object pre$iousl%
referenced b% c1 is no lon"er
referenced.
E
This object is -nown as "arba"e, which
is automaticall% collected b% )a$a
Virtual achine ()V).
c1


Object tpe assignment c1 @ c2


Ce#ore,





c2





c1


A#ter,


c2


c1, Circle
radius @ *

C2, Circle
radius @ 8







c1, Circle
radius @ *

C2, Circle
radius @ 8

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
32
Darbage Collection& cont
T=K4 =f %ou -now that an
object is no lon"er needed,
%ou can e;plicitl% assi"n
null to a reference
$ariable for the object.
The )V will automaticall%
collect the space if the
object is not referenced b%
an% $ariables.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
33
)!e -ate Class
)a$a pro$ides a s%stem/independent encapsulation
of date and time in the ja$a.util.'ate class. Lou
can use the 'ate class to create an instance for
the current date and time and use its toAtrin"
method to return the date and time as a strin".

java.util.-ate
F-ate()
F-ate(elapse)ime, long)
Fto?tring(), ?tring
Fget)ime(), long
Fset)ime(elapse)ime, long), void

Constructs a -ate object #or t!e current time.
Constructs a -ate object #or a given time in
milliseconds elapsed since 2anuar 1& 1830& D/).
7eturns a string representing t!e date and time.
7eturns t!e number o# milliseconds since 2anuar 1&
1830& D/).
?ets a ne" elapse time in t!e object.

)!e F sign indicates
public modi#er


Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
34
)!e -ate Class B%ample
*or e;ample, the followin" code

ja$a.util.'ate date 7 new ja$a.util.'ate()8


A%stem.out.println(date.toAtrin"())8
displa%s a strin" li-e Aun ar 20
1#4+2410 :AT 222#.
import java.util.GA
-ate date @ ne" -ate()A
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3*
)!e 7andom Class
Lou ha$e used ath.random() to obtain a random
double $alue between 2.2 and 1.2 (e;cludin"
1.2). > more useful random number "enerator is
pro$ided in the ja$a.util.(andom class.

java.util.7andom
F7andom()
F7andom(seed, long)
Fne%t<nt(), int
Fne%t<nt(n, int), int
Fne%t6ong(), long
Fne%t-ouble(), double
Fne%t$loat(), #loat
Fne%tCoolean(), boolean

Constructs a 7andom object "it! t!e current time as its seed.
Constructs a 7andom object "it! a speci#ied seed.
7eturns a random int value.
7eturns a random int value bet"een 0 and n (e%clusive).
7eturns a random long value.
7eturns a random double value bet"een 0.0 and 1.0 (e%clusive).
7eturns a random #loat value bet"een 0.0$ and 1.0$ (e%clusive).
7eturns a random boolean value.

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
31
)!e 7andom Class B%ample
=f two (andom objects ha$e the same seed, the% will "enerate
identical seMuences of numbers. *or e;ample, the followin"
code creates two (andom objects with the same seed #.
ando+ rando+1 = new ando+(#);
*1ste+.out.)rint(25ro+ rando+16 2);
for (int i = 0; i 7 10; i44)
*1ste+.out.)rint(rando+1.ne8t9nt(1000) 4 2 2);
ando+ rando+: = new ando+(#);
*1ste+.out.)rint(2.n5ro+ rando+:6 2);
for (int i = 0; i 7 10; i44)
*1ste+.out.)rint(rando+:.ne8t9nt(1000) 4 2 2);
$rom random1, 334 110 210 *41 124 202 *48 *14 4*8 811
$rom random2, 334 110 210 *41 124 202 *48 *14 4*8 811
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
33
-isplaing D5< Components
Nhen %ou de$elop pro"rams to create
"raphical user interfaces, %ou will use
)a$a classes such as )*rame, )Outton,
)(adioOutton, )ComboOo;, and )!ist to
create frames, buttons, radio buttons,
combo bo;es, lists, and so on. !istin" 7.#
is an e;ample that creates two windows
usin" the )*rame class. The output of the
pro"ram is shown in *i"ure 7.12.
TestFrame
TestFrame
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
34
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
-eclare& create& and
assign in one
statement
re#erence #rame1
, 2$rame
title,
"idt!,
!eig!t,
visible,
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
38
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A 2$rame
#rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!,
!eig!t,
visible,
?et title propert
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
40
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!, 200
!eig!t, 1*0
visible,
?et si;e propert
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
41
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!, 200
!eig!t, 1*0
visible, true
?et visible
propert
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
42
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!, 200
!eig!t, 1*0
visible, true
-eclare& create& and
assign in one
statement
re#erence #rame2
, 2$rame
title,
"idt!,
!eig!t,
visible,
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
43
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!, 200
!eig!t, 1*0
visible, true
re#erence #rame2
, 2$rame
title, HIindo" 2H
"idt!,
!eig!t,
visible,
?et title propert
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
44
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!, 200
!eig!t, 1*0
visible, true
re#erence #rame2
, 2$rame
title, HIindo" 2H
"idt!, 200
!eig!t, 1*0
visible,
?et si;e propert
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
4*
)race Code
2$rame #rame1 @ new 2$rame()A
#rame1.set)itle(HIindo" 1H)A
#rame1.set?i;e(200& 1*0)A
#rame1.set=isible(true)A
2$rame #rame2 @ new 2$rame()A
#rame2.set)itle(HIindo" 2H)A
#rame2.set?i;e(200& 1*0)A
#rame2.set=isible(true)A
re#erence #rame1
, 2$rame
title, HIindo" 1H
"idt!, 200
!eig!t, 1*0
visible, true
re#erence #rame2
, 2$rame
title, HIindo" 2H
"idt!, 200
!eig!t, 1*0
visible, true
?et visible
propert
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
41
Adding D5< Components to Iindo"
Lou can add "raphical user interface
components, such as buttons, labels,
te;t fields, combo bo;es, lists, and
menus, to the window. The components are
defined usin" classes. !istin" 7.& "i$es
an e;ample to create buttons, labels,
te;t fields, chec- bo;es, radio buttons,
and combo bo;es, as shown in *i"ure 7.1.
G!Components
G!Components
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
43
<nstance
=ariables& and /et!ods
<nstance variables belong to a speci#ic instance.
<nstance met!ods are invo'ed b an instance o#
t!e class.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
44
?tatic =ariables& Constants&
and /et!ods
?tatic variables are s!ared b all t!e instances o# t!e
class.
?tatic met!ods are not tied to a speci#ic object.
?tatic constants are #inal variables s!ared b all t!e
instances o# t!e class.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
48
?tatic =ariables& Constants&
and /et!ods& cont.
)o declare static variables& constants& and met!ods&
use t!e static modi#ier.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*0
?tatic =ariables& Constants&
and /et!ods& cont.

Circle

radius, double
numberO#Objects, int

get+umberO#Objects(), int
FgetArea(), double
1
radius
circle1

radius @ 1
numberO#Objects @ 2

instantiate
instantiate
/emor
2
*
radius
numberO#Objects
5/6 +otation,
F, public variables or met!ods
underline, static variables or met!ods

circle2

radius @ *
numberO#Objects @ 2

A#ter t"o Circle
objects "ere created&
numberO#Objects
is 2.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*1
B%ample o#
5sing <nstance and Class =ariables
and /et!od
3bjecti$e4 'emonstrate the roles
of instance and class $ariables
and their uses. This e;ample adds
a class $ariable number3f3bjects
to trac- the number of Circle
objects created.
TestCircle"
TestCircle"
Circle"
Circle"
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*2
=isibilit /odi#iers and
Accessor>/utator /et!ods
O% default, the class, $ariable, or method
can be
accessed b% an% class in the same pac-a"e.
!
)ublic
)!e class& data& or met!od is visible to an class in an
pac'age.
!
)ri,ate
)!e data or met!ods can be accessed onl b t!e declaring
class.
)!e get and set met!ods are used to read and modi# private
properties.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*3
)!e private modi#ier restricts access to "it!in a class& t!e de#ault
modi#ier restricts access to "it!in a pac'age& and t!e public
modi#ier enables unrestricted access.

)ublic class C1 {
)ublic int 8;
int 1;
)ri,ate int ;;

)ublic ,oid +1() {
}
,oid +:() {
}
)ri,ate ,oid +#() {
}
}
)ublic class C: {
,oid a(ethod() {
C1 o = new C1();
can access o.8;
can access o.1;
cannot access o.;;

can in,o<e o.+1();
can in,o<e o.+:();
cannot in,o<e o.+#();
}
}
pac'age p1A
pac'age p2A
)ublic class C# {
,oid a(ethod() {
C1 o = new C1();
can access o.8;
cannot access o.1;
cannot access o.;;

can in,o<e o.+1();
cannot in,o<e o.+:();
cannot in,o<e o.+#();
}
}

class C1 {
...
}
)ublic class C: {
can access C1
}
pac'age p1A
pac'age p2A
)ublic class C# {
cannot access C1;
can access C:;
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*4
)!e private modi#ier restricts access to "it!in a class& t!e de#ault
modi#ier restricts access to "it!in a pac'age& and t!e public
modi#ier enables unrestricted access.

)ublic class C1 {
)ublic int 8;
int 1;
)ri,ate int ;;
)rotected int w;

)ublic ,oid +1() {
}
,oid +:() {
}
)ri,ate ,oid +#() {
}
}
)ublic class C: {
,oid a(ethod() {
C1 o = new C1();
can access o.8;
can access o.1;
cannot access o.;;
can access o.w

can in,o<e o.+1();
can in,o<e o.+:();
cannot in,o<e o.+#();
}
}
pac'age p1A
pac'age p2A
)ublic class C# {
,oid a(ethod() {
C1 o = new C1();
can access o.8;
cannot access o.1;
cannot access o.;;
cannot access o.w;
can in,o<e o.+1();
cannot in,o<e o.+:();
cannot in,o<e o.+#();
}
}

class C1 {
...
}
)ublic class C: {
can access C1
}
pac'age p1A
pac'age p2A
)ublic class C# {
cannot access C1;
can access C:;
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
**
+O)B
An object cannot access its private members& as s!o"n in (b).
<t is OJ& !o"ever& i# t!e object is declared in its o"n class& as
s!o"n in (a).

)ublic class 5oo {
)ri,ate boolean 8;

)ublic static ,oid +ain(*trin!/0 ar!s) {
5oo foo = new 5oo();
*1ste+.out.)rintln(foo.8);
*1ste+.out.)rintln(foo.con,ert());
}

)ri,ate int con,ert(boolean b) {
return 8 3 1 6 =1;
}
}



(a) )!is is OJ because object #oo is used inside t!e $oo class
)ublic class Test {
)ublic static ,oid +ain(*trin!/0 ar!s) {
5oo foo = new 5oo();
*1ste+.out.)rintln(foo.8);
*1ste+.out.)rintln(foo.con,ert(foo.8));
}
}


(b) )!is is "rong because % and convert are private in $oo.

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*1
I! -ata $ields ?!ould Ce
privateK
To protect data.
To ma-e class eas% to maintain.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*3
B%ample o#
-ata $ield Bncapsulation
Circle#
Circle#
TestCircle#
TestCircle#

Circle
-radius, double
-numberO#Objects, int

FCircle()
FCircle(radius, double)
Fget7adius(), double
Fset7adius(radius, double), void
Fget+umberO#Object(), int
FgetArea(), double


)!e radius o# t!is circle (de#ault, 1.0).
)!e number o# circle objects created.

Constructs a de#ault circle object.
Constructs a circle object "it! t!e speci#ied radius.
7eturns t!e radius o# t!is circle.
?ets a ne" radius #or t!is circle.
7eturns t!e number o# circle objects created.
7eturns t!e area o# t!is circle.

)!e - sign indicates
private modi#ier


Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*4
Passing Objects to /et!ods
!
Kassin" b% $alue for primiti$e t%pe $alue
(the $alue is passed to the parameter)
!
Kassin" b% $alue for reference t%pe $alue
(the $alue is the reference to the
object)
Test$assObject
Test$assObject
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*8
Passing Objects to /et!ods& cont.

?pace re(uired #or t!e
main met!od
int n, *
mCircle,


?tac'

?pace re(uired #or t!e
printAreas met!od
int times, *
Circle c,
re#erence
A circle
object

Leap



re#erence
Pass b value
(!ere t!e value is
t!e re#erence #or
t!e object)
Pass b value (!ere
t!e value is *)
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
10
Arra o# Objects
CircleFG circle>rra% 7 new CircleF12G8
> Circle arra% is actuall%
an array of reference
variables.
re#erence

circleArraM0N


O
circleArra
circleArraM1N



circleArraM8N


Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
11
Arra o# Objects& cont.

re#erence

Circle object 0
circleArraM0N


O
circleArra
circleArraM1N



circleArraM8N


Circle object 8
Circle object 1
CircleFG circle>rra% 7 new CircleF12G8
for (int i728 i P 128 JJi)
circle>rra%FiG 7 new Circle()8
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
12
Arra o# Objects& cont.
<nvo'ing circleArraM1N.getArea() involves t"o levels
o# re#erencing as s!o"n in t!e ne%t #igure. circleArra
re#erences to t!e entire arra. circleArraM1N re#erences
to a Circle object.

re#erence

Circle object 0
circleArraM0N


O
circleArra
circleArraM1N



circleArraM8N


Circle object 8
Circle object 1
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
13
Arra o# Objects& cont.
AummariQin" the areas of
the circles

Total%rea
Total%rea
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
<nitiali;ation o# <nstance $ields
!
Ae$eral wa%s4
1.:;plicit initialiQation
2.=nitialiQer
(or initialiQation) bloc-
#.Constructors
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
!
:;plicit initialiQation4
initialiQation at declaration.
pri$ate double salar% 7 2.28
pri$ate Atrin" name 7 BC8
<nitiali;ation o# <nstance $ields
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
!
=nitialiQer (or initialiQation) bloc-4
E
Class declaration can contain arbitrar%
bloc-s of codes.
class :mplo%ee
5 R
pri$ate int id8
pri$ate static int ne;t=d718
HH object initialiQer bloc-
5
id 7 ne;t=d8
ne;t=dJJ8
6
R
6
<nitiali;ation o# <nstance $ields
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
!
=nitialiQation b% constructors
class :mplo%ee
5
R
pri$ate int id8
pri$ate static int ne;t=d718
:mplo%ee()5
id 7 ne;t=d8
ne;t=dJJ8
6
6
<nitiali;ation o# <nstance $ields
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
!
Nhat happens when a constructor is called
E
>ll data fields initialiQed to their default
$alue (2, false, null)
E
*ield initialiQers and instance initialiQer
bloc-s are e;ecuted accordin" to their order of
appearance
E
Ood% of the constructor is e;ecuted after the
bod% of its superclass<s constructor
N
+ote t!at a constructor mig!t call anot!er constructor at line 1.
<nitiali;ation o# <nstance $ields
instance$ield<nitiali;ation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
!
Nhat happens when a class is loaded
E
>ll static data fields initialiQed to their
default $alue (2, false, null)
E
Atatic field initialiQers and static
initialiQer bloc-s are e;ecuted in the
order of their appearance
E
9ote that static fields are initialiQed
once when its parent class is loaded.
<nitiali;ation o# ?tatic $ields
?tatic$ield<nitiali;ation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1
Inheritance and Polymorphism
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2
Motivations
Suppose you will define classes to model circles, rectangles, and triangles.
These classes have many common features.
What is the est way to design these classes so to avoid redundancy!
The answer is to use inheritance.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"
#$ectives
N
To develop a suclass from a superclass through inheritance %&1'.2(.
N
To invo)e the superclass*s constructors and methods using the super )eyword
%&1'."(.
N
To override methods in the suclass %&1'.+(.
N
To distinguish differences etween overriding and overloading %&1'.,(.
N
To e-plore the useful methods toString%( and e.uals%#$ect( in the #$ect class
%&1'./(.
N
To comprehend polymorphism, dynamic inding, and generic programming
%&1'.0(.
N
To descrie casting and e-plain why e-plicit downcasting is necessary %&1'.1(.
N
To store, retrieve, and manipulate o$ects in an 2rray3ist %&1'.4(.
N
To implement a Stac) class using 2rray3ist %&1'.1'(.
N
To restrict access to data and methods using the protected visiility modifier
%&1'.11(.
N
To prevent class e-tending and method overriding using the final modifier
%&1'.12(.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+
Superclasses and Suclasses

5eometric#$ect
6color7 String
6filled7 oolean
6date8reated7 $ava.util.9ate
:5eometric#$ect%(
:get8olor%(7 String
:set8olor%color7 String(7 void
:is;illed%(7 oolean
:set;illed%filled7 oolean(7 void
:get9ate8reated%(7 $ava.util.9ate
:toString%(7 String
The color of the o$ect %default7 white(.
Indicates whether the o$ect is filled with a color %default7 false(.
The date when the o$ect was created.
8reates a 5eometric#$ect.
<eturns the color.
Sets a new color.
<eturns the filled property.
Sets a new filled property.
<eturns the date8reated.
<eturns a string representation of this o$ect.
8ircle
6radius7 doule
:8ircle%(
:8ircle%radius7 doule(
:get<adius%(7 doule
:set<adius%radius7 doule(7 void
:get2rea%(7 doule
:getPerimeter%(7 doule
:get9iameter%(7 doule

<ectangle
6width7 doule
6height7 doule
:<ectangle%(
:<ectangle%width7 doule, height7 doule(
:getWidth%(7 doule
:setWidth%width7 doule(7 void
:get=eight%(7 doule
:set=eight%height7 doule(7 void
:get2rea%(7 doule
:getPerimeter%(7 doule

GeometricObject1
GeometricObject1
Circle4
Circle4
Rectangle1
Rectangle1
TestCircleRectangle
TestCircleRectangle
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
,
>-tending the ?;rame 8lass
In the introduction of this chapter, we proposed the
prolem of creating two identical windows with the
same components. This prolem can e effectively
solved using inheritance.
UseCustomFrame
UseCustomFrame
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
/
2re superclass*s 8onstructor
Inherited!
@o. They are not inherited.
They are invo)ed e-plicitly or implicitly.
>-plicitly using the super )eyword.
2 constructor is used to construct an instance of a class.
Anli)e properties and methods, a superclassBs
constructors are not inherited in the suclass. They can
only e invo)ed from the suclassesB constructors, using
the )eyword super. If the keyword super is not explicitly
used, the superclass's no-arg constructor is
automatically invoked.
8onstructorInheritanceTest
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
0
Superclass*s 8onstructor Is 2lways Invo)ed
2 constructor may invo)e an overloaded constructor or its
superclass*s constructor. If none of them is invo)ed
e-plicitly, the compiler puts super%( as the first statement
in the constructor. ;or e-ample,

public A(double d) {
// some statements
}

is e.uivalent to

public A(double d) {
super();
// some statements
}

public A() {
}

is e.uivalent to

public A() {
super();
}
8onstructorInheritanceTest
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1
Asing the Ceyword super
!
To call a superclass constructor
!
To call a superclass method
The )eyword super refers to the superclass
of the class in which super appears. This
)eyword can e used in two ways7
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
4
82ATI#@
Dou must use the )eyword super to call the
superclass constructor. Invo)ing a
superclass constructor*s name in a suclass
causes a synta- error. ?ava re.uires that the
statement that uses the )eyword super
appear first in the constructor.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1'
8onstructor 8haining
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
8onstructing an instance of a class invo)es all the superclasses* constructors
along the inheritance chain. This is called constructor chaining.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
11
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
1. Start from the main
method
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
12
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
2. Invo)e ;aculty
constructor
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1"
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
". Invo)e >mployee*s no6arg
constructor
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1+
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
+. Invo)e >mployee%String(
constructor
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1,
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
,. Invo)e Person%( constructor
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1/
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
/. >-ecute println
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
10
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
0. >-ecute println
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
11
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
1. >-ecute println
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
14
Trace >-ecution
public class Faculty extends Employee {
public static void main(String[ args) {
ne! Faculty();
}

public Faculty() {
System"out"println(#($) Faculty%s no&arg constructor is invo'ed#);
}
}

class Employee extends (erson {
public Employee() {
t)is(#(*) +nvo'e Employee,s overloaded constructor#);
System"out"println(#(-) Employee%s no&arg constructor is invo'ed#);
}

public Employee(String s) {
System"out"println(s);
}
}

class (erson {
public (erson() {
System"out"println(#(.) (erson%s no&arg constructor is invo'ed#);
}
}
4. >-ecute println
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2'
>-ample on the Impact of a Superclass
without no6arg 8onstructor
public class Apple extends Fruit {
}

class Fruit {
public Fruit(String name) {
System"out"println(#Fruit%s constructor is invo'ed#);
}
}
;ind out the errors in the program7
Test@o2rg8onstructor
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
21
9eclaring a Suclass
2 suclass e-tends properties and methods from the
superclass. Dou can also7
!
2dd new properties
!
2dd new methods
!
#verride the methods of the superclass
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
22
8alling Superclass Methods
Dou could rewrite the print8ircle%( method in the 8ircle class as
follows7
pulic void print8ircle%( E
System.out.println%FThe circle is created F :
super.get9ate8reated%( : F and the radius is F : radius(G
H
8ircle+
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2"
#verriding Methods in the Superclass
2 suclass inherits methods from a superclass. Sometimes it is
necessary for the suclass to modify the implementation of a method
defined in the superclass. This is referred to as method overriding.
public class /ircle extends 0eometric1b2ect {
// 1t)er met)ods are omitted
/33 1verride t)e toString met)od de4ined in 0eometric1b2ect 3/
public String toString() {
return super"toString() 5 #6nradius is # 5 radius;
}
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2+
@#T>
2n instance method can e overridden only
if it is accessile. Thus a private method
cannot e overridden, ecause it is not
accessile outside its own class. If a method
defined in a suclass is private in its
superclass, the two methods are completely
unrelated.
Test
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
!
class 2 E protected void mymethod%(G H
!
class I e-tends 2 E
J
pulic void mymethod%(GH
2,
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2/
@#T>
3i)e an instance method, a static method
can e inherited. =owever, a static method
cannot e overridden. If a static method
defined in the superclass is redefined in a
suclass, the method defined in the
superclass is hidden.
StaticTest
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
20
#verriding vs. #verloading

public class 7est {
public static void main(String[ args) {
A a 8 new A();
a"p(.9);
a"p(.9"9);
}
}

class : {
public void p(double i) {
System"out"println(i 3 *);
}
}

class A extends : {
// 7)is met)od overrides t)e met)od in :
public void p(double i) {
System"out"println(i);
}
}

public class 7est {
public static void main(String[ args) {
A a 8 new A();
a"p(.9);
a"p(.9"9);
}
}

class : {
public void p(double i) {
System"out"println(i 3 *);
}
}

class A extends : {
// 7)is met)od overloads t)e met)od in :
public void p(int i) {
System"out"println(i);
}
}

Test
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
21
The #$ect 8lass and Its Methods
>very class in ?ava is descended from the
$ava.lang.#$ect class. If no inheritance is
specified when a class is defined, the
superclass of the class is #$ect.

public class /ircle {
"""
}

>.uivalent
public class /ircle extends 1b2ect {
"""
}

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
24
The toString%( method in #$ect
The toString%( method returns a string representation of the
o$ect. The default implementation returns a string consisting of
a class name of which the o$ect is an instance, the at sign %K(,
and a he-adecimal value representing this o$ect*s hashcode.
3oan loan L new 3oan%(G
System.out.println%loan.toString%((G
The code displays something li)e 3oanK1,'"0e, . This
message is not very helpful or informative. Asually you should
override the toString method so that it returns a digestile string
representation of the o$ect.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"'
The e;uals Method
The e;uals() method compares the
contents of two o$ects. The default implementation of the
e.uals method in the #$ect class is as follows7
public boolean e;uals(1b2ect ob2) {
return (t)is 88 ob2);
}
For example< t)e
e;uals met)od is
overridden in
t)e /ircle
class"
public boolean e;uals(1b2ect o) {
i4 (o instanceo4 /ircle) {
return radius 88 ((/ircle)o)"radius;
}
else
return 4alse;
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"1
@#T>
The LL comparison operator is used for
comparing two primitive data type values or for
determining whether two o$ects have the same
references. The e.uals method is intended to
test whether two o$ects have the same
contents, provided that the method is modified
in the defining class of the o$ects. The LL
operator is stronger than the e.uals method, in
that the LL operator chec)s whether the two
reference variales refer to the same o$ect.
8ircle+
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"2
9ynamic Iinding
9ynamic inding wor)s as follows7 Suppose an o$ect o is an
instance of classes 8
1
, 8
2
, ..., 8
n61
, and 8
n
, where 8
1
is a suclass
of 8
2
, 8
2
is a suclass of 8
"
, ..., and 8
n61
is a suclass of 8
n
. That
is, 8
n
is the most general class, and 8
1
is the most specific class.
In ?ava, 8
n
is the #$ect class. If o invo)es a method p, the ?MM
searches the implementation for the method p in 8
1
, 8
2
, ..., 8
n61
and 8
n
, in this order, until it is found. #nce an implementation is
found, the search stops and the first6found implementation is
invo)ed.

8
n
8
n61

. . . . .
8
2
8
1

#$ect
Since o is an instance of 8
1
, o is also an
instance of 8
2,
8
",
N, 8
n61
, and 8
n

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
""
Method Matching vs. Iinding
Matching a method signature and inding a method
implementation are two issues. The compiler finds a
matching method according to parameter type, numer
of parameters, and order of the parameters at
compilation time. 2 method may e implemented in
several suclasses. The ?ava Mirtual Machine
dynamically inds the implementation of the method at
runtime.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"+
Polymorphism, 9ynamic Iinding and 5eneric Programming
public class (olymorp)ism=emo {
public static void main(String[ args) {
m(ne! 0raduateStudent());
m(ne! Student());
m(ne! (erson());
m(ne! 1b2ect());
}

public static void m(1b2ect x) {
System"out"println(x"toString());
}
}

class 0raduateStudent extends Student {
}

class Student extends (erson {
public String toString() {
return #Student#;
}
}

class (erson extends 1b2ect {
public String toString() {
return #(erson#;
}
}
Method m ta)es a parameter
of the #$ect type. Dou can
invo)e it with any o$ect.
2n o$ect of a sutype can e used wherever its
supertype value is re.uired. This feature is
)nown as polymorphism.
When the method m%#$ect -( is e-ecuted, the
argument -*s toString method is invo)ed. -
may e an instance of 5raduateStudent,
Student, Person, or #$ect. 8lasses
5raduateStudent, Student, Person, and #$ect
have their own implementation of the toString
method. Which implementation is used will e
determined dynamically y the ?ava Mirtual
Machine at runtime. This capaility is )nown
as dynamic binding.
PolymorphismDemo
PolymorphismDemo
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
",
8asting #$ects
Dou have already used the casting operator to convert variales of
one primitive type to another. Casting can also e used to convert an
o$ect of one class type to another within an inheritance hierarchy. In
the preceding section, the statement
m%new Student%((G
assigns the o$ect new Student%( to a parameter of the #$ect type.
This statement is e.uivalent to7
#$ect o L new Student%(G OO Implicit casting
m%o(G
The statement #$ect o L new Student%(, )nown as
implicit casting, is legal ecause an instance of
Student is automatically an instance of #$ect.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"/
Why 8asting Is @ecessary!
Suppose you want to assign the o$ect reference o to a variale of the
Student type using the following statement7
Student L oG

2 compilation error would occur. Why does the statement Object o =
new Student() wor) and the statement Student b = o doesn*t! This is
ecause a Student o$ect is always an instance of #$ect, ut an
#$ect is not necessarily an instance of Student. >ven though you can
see that o is really a Student o$ect, the compiler is not so clever to
)now it. To tell the compiler that o is a Student o$ect, use an e-plicit
casting. The synta- is similar to the one used for casting among
primitive data types. >nclose the target o$ect type in parentheses and
place it efore the o$ect to e cast, as follows7
Student L %Student(oG OO >-plicit casting
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"0
8asting from
Superclass to Suclass
>-plicit casting must e used when casting an o$ect from a superclass to
a suclass. This type of casting may not always succeed.
Apple x 8 (Apple)4ruit;
1range x 8 (1range)4ruit;
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"1
The instanceo4 #perator
Ase the instanceo4 operator to test whether an o$ect is an instance
of a class7
Object myObject = new Circle();
... // Some lines of code
/ !erform castin" if myObject is an instance of
Circle /
if (myObject instanceof Circle) #
System.out.println($%&e circle diameter is $ '
((Circle)myObject)."et(iameter());
...
)
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
"4
TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the ;ruit class as the superclass
for 2pple and #range. 2n apple is a fruit, so
you can always safely assign an instance of
2pple to a variale for ;ruit. =owever, a
fruit is not necessarily an apple, so you have
to use e-plicit casting to assign an instance of
;ruit to a variale of 2pple.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+'
>-ample7 Demonstrating
Polymorphism and Casting
This e-ample creates two geometric o$ects7 a
circle, and a rectangle, invo)es the
display5eometric#$ect method to display the
o$ects. The display5eometric#$ect displays
the area and diameter if the o$ect is a circle, and
displays area if the o$ect is a rectangle.
TestPolymorphismCasting
TestPolymorphismCasting
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+1
The 2rray3ist and Mector 8lasses
Dou can create an array to store o$ects. Iut the array*s siPe is fi-ed
once the array is created. ?ava provides the 2rray3ist class that can
e used to store an unlimited numer of o$ects.

$ava.util.2rray3ist
:2rray3ist%(
:add%o7 #$ect( 7 void
:add%inde-7 int, o7 #$ect( 7 void
:clear%(7 void
:contains%o7 #$ect(7 oolean
:get%inde-7 int( 7 #$ect
:inde-#f%o7 #$ect( 7 int
:is>mpty%(7 oolean
:lastInde-#f%o7 #$ect( 7 int
:remove%o7 #$ect(7 oolean
:siPe%(7 int
:remove%inde-7 int( 7 #$ect
:set%inde-7 int, o7 #$ect( 7 #$ect

2ppends a new element o at the end of this list.
2dds a new element o at the specified inde- in this list.
<emoves all the elements from this list.
<eturns true if this list contains the element o.
<eturns the element from this list at the specified inde-.
<eturns the inde- of the first matching element in this list.
<eturns true if this list contains no elements.
<eturns the inde- of the last matching element in this list.
<emoves the element o from this list.
<eturns the numer of elements in this list.
<emoves the element at the specified inde-.
Sets the element at the specified inde-.

8reates an empty list.


Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+2
?9C Warning
Dou will get a compilation warning Qunchec)ed operationR. Ignore it. This
warning can e fi-ed using generic types7 2rray3istSStringT and
2rray3istS8ircle+T.
TestArrayList
TestArrayList
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+"
The MyStac) 8lasses
2 stac) to hold o$ects.

MyStac)
6list7 2rray3ist
:is>mpty%(7 oolean
:getSiPe%(7 int
:pee)%(7 #$ect
:pop%(7 #$ect
:push%o7 #$ect(7 #$ect
:search%o7 #$ect(7 int


<eturns true if this stac) is empty.
<eturns the numer of elements in this stac).
<eturns the top element in this stac).
<eturns and removes the top element in this stac).
2dds a new element to the top of this stac).
<eturns the position of the first element in the stac) from
the top that matches the specified element.

2 list to store elements.



y!tac"
y!tac"
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
++
The protected Modifier
!
The protected modifier can e applied on data
and methods in a class. 2 protected data or a
protected method in a pulic class can e accessed
y any class in the same pac)age or its suclasses,
even if the suclasses are in a different pac)age.
!
private, default, protected, pulic

private< none (i4 no modi4ier is used)< protected< public
>isibility increases
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+,
2ccessiility Summary

Modifier
on memers
in a class
2ccessed
from the
same class
2ccessed
from the
same pac)age
2ccessed
from a
suclass
2ccessed
from a different
pac)age
pulic
protected
&
default
&
&
private
& &
&
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+/
Misiility Modifiers

public class /. {
public int x;
protected int y;
int ?;
private int u;

protected void m() {
}
}
public class /* {
/. o 8 ne! /.();
can access o"x;
can access o"y;
can access o"?;
cannot access o"u;

can invo'e o"m();
}
public class /-
extends /. {
can access x;
can access y;
can access ?;
cannot access u;

can invo'e m();
}
pac)age p1G
public class /$
extends /. {
can access x;
can access y;
cannot access ?;
cannot access u;

can invo'e m();
}
pac)age p2G
public class /@ {
/. o 8 ne! /.();
can access o"x;
cannot access o"y;
cannot access o"?;
cannot access o"u;

cannot invo'e o"m();
}
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+0
2 Suclass 8annot Wea)en the 2ccessiility
2 suclass may override a protected
method in its superclass and change its
visiility to pulic. =owever, a suclass
cannot wea)en the accessiility of a
method defined in the superclass. ;or
e-ample, if a method is defined as pulic
in the superclass, it must e defined as
pulic in the suclass.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+1
@#T>
The modifiers are used on classes and
class memers %data and methods(, e-cept
that the final modifier can also e used on
local variales in a method. 2 final local
variale is a constant inside a method.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
+4
The 4inal Modifier
!
The 4inal class cannot e e-tended7
final class *at& #
...
)
!
The 4inal variale is a constant7
final static double !+ = ,.-.-/0;
!
The 4inal method cannot e
overridden y its suclasses.
1
Unit Testing & JUnit
What is unit testing?
!
A unit typically refers to a method in a Java class.
!
A unit test case is a test execution of a Java method.
!
A test suites is a careful selected set of unit test cases.
2
Why unit testing?
Rectangle
height: int
width: int
resize(double, double)
getArea(): int
getPerieter(): int
!
Method signatures do not tell us what
the method does.
!
Even a method comes with comments,
we do not know if the method faithfully
implements its comments.
!
We need an effective and highly
automated mechanism to recheck if the
code still works after any changes.
!
Why is Unit Testing "ood?
!
Identifies defects early in the development cycle.
!
Many small ugs ultimately leads to chaotic system ehavior
!
!esting affects the design of your code.
!
"uccessful tests reed confidence.
!
!esting forces us to read our own code # spend more time reading than
writing
!
Automated tests support maintainaility and extendiility.
What is JUnit?
!
J$nit is a regression testing framework written y Enrich %amma
and &ent 'eck.
!
It is a de facto framework used y Java practitioners to test their
code.
!
J$nit is (pen "ource "oftware hosted on "ource)orge.
!
It is a uilt*in Eclipse plug*in.
!
Its latest version is +.,.
#
A JUnit Test $ase
!
!est runs automatically with little human participation.
!
-esults are either pass or fail.
!
-esults are reproducile and consistent.
%
@Test
public void testGetArea() {
Rectangle r = new Rectangle(2, 4);
double expectedArea = 2 * 4;
double actualArea = rgetArea();
assertEquals("getArea fails", expectedArea, actualArea,
0.000001);
}
What is in a test &ase?
!
.escrie the method/s input
!
.escrie the expected output
!
0all the method and oserve actual output
!
0ompare expected with actual output, and 1udge if the test case
passes or fails
'
@Test
public void testGetArea() {
Rectangle r = new Rectangle(2, 4);
double expectedArea = 2 * 4;
double actualArea = rgetArea();
assertEquals("getArea fails", expectedArea, actualArea,
0.000001);
}
(e)ore and A)ter ea&h test &ase
*
@Before
public void setUp() throws Exception {
++ $reate ob,e&ts and &oon -ariables )or your tests here
++ setU.() is &alled be)ore /A$0 test &ase is run
}
@After
public void tearDown() throws Exception {
++ .ut &ode here to reset or release ob,e&ts, e1g1, .12null3
++ to garbage &olle&t unused ob,e&ts or resour&es
++ tear4o5n() is &alled a)ter /A$0 test &ase is run
}
0o5 a test suite is e6e&uted
7
! @setUp()
"! Test case
#! @tearDown()
$! @setUp()
%! Test case "
&! @tearDown()
111 until all test &ases are e6e&uted
8
/a&h test is inde.endent o) the .re-ious ones
4oes e6.e&ted 2 a&tual?
!
!o compare any variales of the 2 Java primitive types
3i.e., oolean, yte, short, int, long, char, float, doule4
use5
assertE'uals(expected( actual)
!
)irst argument 3optional4 is a string printed when the
assertion fails5
assertE'uals()essa*e( expected( actual)
19
$o.arisons )or Priiti-e Ty.es
!
assertE'uals(int expected( int actual)
!
assertE'uals(boolean expected( boolean actual)
!
assertE'uals(b+te expected( b+te actual)
!
assertE'uals(char expected( char actual)
!
assertE'uals(short expected( short actual)
!
assertE'uals(lon* expected( lon* actual)
!
assertE'uals(double expected( double actual(
double tolerance)
!
assertE'uals(float expected( float actual( float
tolerance)
!
Each of them supports a variant method y specifying a failure
message string as the first formal parameter.
11
:ore Assertions
!
assert)alse3condition4
!
assert)alse3message, condition4
!
assert6ot6ull3o1ect4
!
assert6ot6ull3message, o1ect4
!
assert6ot"ame3expected, actual4
!
assert6ot"ame3message, expected,
actual4
!
assert6ull3o1ect4
!
assert6ull3message, o1ect4
!
assert"ame3expected, actual4
!
assert"ame3message, expected,
actual4
!
assert!rue3condition4
!
assert!rue3message, condition4
!
fail34
!
fail3message4
!
fail6otE7uals3message, expected,
actual4
!
fail6ot"ame3message, expected,
actual4
!
fail"ame3message4
12
/&li.se 4eonstration
1!
pulic class -ectangle!est 8
9'efore0lass
pulic static void set$p'efore0lass34 throws Exception 8
:
9After0lass
pulic static void tear.ownAfter0lass34 throws Exception 8
:
9'efore
pulic void set$p34 throws Exception 8
r ; new -ectangle3+, +4<
:
9After
pulic void tear.own34 throws Exception 8
r ; null<
:
9!est
pulic void test%etArea34 8
doule expectedArea ; width = height<
doule actualArea ; r.getArea34<
assertEquals("getArea fails", expectedArea, actualArea,
tolerance);
:
9!est
pulic void test-esi>e34 8
r.resi>e3?.@A, @4<
assertEquals("resize - height fails", 0.2!height,
r.get"eight(), tolerance);
assertEquals("resize - #idth fails", 2!#idth, r.get$idth(),
tolerance);
:
-ectangle r<
final int height ; +, width ; +<
final doule tolerance ; ?.?????,<
:
Test ;uites in JUnit <
1<
i!port org"unitrunnerRun#it$;
i!port org"unitrunners%uite;
@,un-ith(.uite!class)
@.uite!.uite/lasses({
0eo)etric1b2ectTest!class(
,ectan*leTest!class,
&
})
public class 'est(ain {
}
4esign o) JUnit =rae5or>
Une6ained su..leentary aterials
)or ad-an&ed reading
1#
JUnit 4esign ?b,e&ti-es
!
A simple framework that encourages developers to write unit
tests.
!
Minimalist framework # essential features, easier to learn, more
likely to e used, flexile
!
!est 0ases B !est -esults are o1ects
!
Catterns # high DdensityE of patterns around key astractions 5
mature framework
JUnit =rae5or> 4esign
;ee the JUnit $oo>@s Tour )or a )ull .attern analysis:
htt.:++,unit1sour&e)orge1net+do&+&oo>stour+&oo>stour1ht
Test$ase
!
!est0ase.run34 applies !emplate Method pattern
.ubli& -oid run()A
setu.()3
runTest()3
tear4o5n()3
B
Define the skeleton of an
algorithm in an operation,
deferring some steps to subclasses
TestCesult
!
!est-esult applies 0ollecting Carameter pattern
.ubli& -oid run(TestCesult result) A
result1startTest(this)3
setU.()3
try A
runTest()3
B
&at&h (Assertion=ailed/rror e) A
result1add=ailure(this, e)3
B
&at&h (Thro5able e) A
result1add/rror(this, e)3
B
)inally A
tear4o5n()3
B
B
When you need to collect results over
several methods, add a parameter to the
method and pass an object that will
collect results for you
(eck ! "malltalk est #ractice #atterns$
Test;uite
!
!est"uite applies 0omposite pattern
%omposite objects into tree structures to represent
part&whole hierarchies' %omposite lets clients treat individual
objects and compositions of objects uniformly
Cesour&es
!
J$nit5 www.1unit.org
!
!esting )rameworks 5 http5FFc@.comFcgiFwikiG!esting)ramework
!
cpp$nit5 http5FFcppunit.sourceforge.netFdocF,.2.?Findex.html
!
"$nit5 http5FFsunit.sourceforge.netF
!
$nit !esting in Java # How !ests .rive the 0ode, Johannes Iink
!
!est*.riven .evelopment y Example, &ent 'eck
!
Cragmatic $nit !esting in Java with J$nit, Andy Hunt B .ave
!homas
!
DIearning to Iove $nit !estingE, !homas B Hunt5
www.pragmaticprogrammer.comFarticlesFst7e*?,*@??@.pdf
System Design Model
Savings Account
creditInterest()
print()
Account
name
balance
getBalance()
setBalance()
print()
Interest
interest rate
attach()
getInterestRate()
setInterestRate()
offerInterest()
* 1 * 1 enjoys
Bank
storeAccount()
printAccounts()
offerInterest()
* 1 * 1
has
*
1
*
1
offers
A bank may
offer many
interests later
System Design Model
Savings Account
creditInterest()
print()
Account
name
balance
getBalance()
setBalance()
print()
Interest
interest rate
attach()
getInterestRate()
setInterestRate()
offerInterest()
* 1 * 1
enjoys
Bank
storeAccount()
printAccounts()
offerInterest()
* 1 * 1
has
*
1
*
1
offers
A bank may
offer many
interests later
Interestarningntity
creditInterest()
!!Interface""
Exercise Revised System Design
Model
Savings Account
creditInterest()
print()
Account
name
balance
getBalance()
setBalance()
print()
Bank
storeAccount()
printAccounts()
offerInterest()
A bank may
offer many
interests later
* 1 * 1
has
#i$ed%epositAccount
creditInterest()
print()
Interest
interest rate
attach()
getInterestRate()
setInterestRate()
offerInterest()
*
1
*
1
offers
Interestarningntity
creditInterest()
!!Interface""
* 1
enjoys
1 *
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1
Abstract Classes and Interfaces
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2
Motivations
You learned how to write simple programs to
display GUI components. Can you write the code
to respond to user actions such as clicking a
button?
HandleEvent
HandleEvent
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3
Objectives
N
To design and use abstract classes (11.2).
N
To rocess a calendar using t!e Calendar and "regorianCalendar classes (11.3).
N
To secif# be!avior for objects using interfaces (11.$).
N
To define interfaces and declare classes t!at i%le%ent interfaces (11.$).
N
To define a natural order using t!e Co%arable interface (11.&).
N
To enable objects to listen for action events using t!e Action'istener interface
(11.().
N
To %a)e objects cloneable using t!e Cloneable interface (11.*).
N
To e+lore t!e si%ilarities and differences bet,een an abstract class and an
interface (11.-).
N
To create objects for ri%itive values using t!e ,raer classes (.#te/ 0!ort/
Integer/ 'ong/ 1loat/ 2ouble/ C!aracter/ and .oolean) (11.3).
N
To create a generic sort %et!od (11.14).
N
To si%lif# rogra%%ing using auto%atic conversion bet,een ri%itive t#es and
,raer class t#es (11.11).
N
To use t!e .igInteger and .ig2eci%al classes for co%uting ver# large nu%bers
,it! arbitrar# recisions (11.12).
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$$
Abstract Classes and Abstract Met!ods
GeometricObject
GeometricObject
Circle
Circle
Rectangle
Rectangle
TestGometricObject
TestGometricObject

GeometricObject
5color6 0tring
5filled6 boolean
5dateCreated6 java.util.2ate
7"eo%etricObject()
7"eo%etricObject(color6 string/
filled6 boolean)
8getColor()6 0t ring
8setColor(color6 0tring)6 void
8is1illed()6 boolean
8set1illed(filled6 boolean)6 void
8get2ateCreated()6 java.util.2ate
8to0tring()6 0tring
+getArea(): double
+getPerimeter(): double


Circle
5radius6 double
8Circle()
8Circle(radius6 double)
8Circle(radius6 double/ color6 string/
filled6 boolean)
8get9adius()6 double
8set9adius(radius6 double)6 void
8get2ia%eter()6 double

9ectangle
5,idt!6 double
5!eig!t6 double
89ectangle()
89ectangle(,idt!6 double/ !eig!t6 double)
89ectangle(,idt!6 double/ !eig!t6 double/
color6 string/ filled6 boolean)
8get:idt!()6 double
8set:idt!(,idt!6 double)6 void
8get;eig!t()6 double
8set;eig!t(!eig!t6 double)6 void

T!e 7 sign indicates
rotected %odifier


Abstract class


Abstract %et!ods
are italici<ed


Met!ods getArea and get=eri%eter are overridden in
Circle and 9ectangle. 0uerclass %et!ods are generall#
o%itted in t!e >M' diagra% for subclasses.


Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&
abstract %et!od in abstract class
An abstract %et!od cannot be contained in a
nonabstract class. If a subclass of an abstract
suerclass does not i%le%ent all t!e abstract
%et!ods/ t!e subclass %ust be declared abstract. In
ot!er ,ords/ in a nonabstract subclass e+tended fro%
an abstract class/ all t!e abstract %et!ods %ust be
i%le%ented/ even if t!e# are not used in t!e
subclass.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
(
object cannot be created fro%
abstract class
An abstract class cannot be instantiated using
t!e ne, oerator/ but #ou can still define its
constructors/ ,!ic! are invo)ed in t!e
constructors of its subclasses. 1or instance/
t!e constructors of "eo%etricObject are
invo)ed in t!e Circle class and t!e 9ectangle
class.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
*
abstract class ,it!out abstract
%et!od
A class t!at contains abstract %et!ods %ust
be abstract. ;o,ever/ it is ossible to declare
an abstract class t!at contains no abstract
%et!ods. In t!is case/ #ou cannot create
instances of t!e class using t!e ne, oerator.
T!is class is used as a base class for defining
a ne, subclass.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
-
suerclass of abstract class %a# be
concrete
A subclass can be abstract even if its
suerclass is concrete. 1or e+a%le/ t!e
Object class is concrete/ but its subclasses/
suc! as "eo%etricObject/ %a# be abstract.
TestAbstract
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3
concrete %et!od overridden to be
abstract
A subclass can override a %et!od fro% its
suerclass to declare it abstract. T!is is rare/
but useful ,!en t!e i%le%entation of t!e
%et!od in t!e suerclass beco%es invalid in
t!e subclass. In t!is case/ t!e subclass %ust be
declared abstract.
ConcreteAbstractTest
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
14
abstract class as t#e
?ou cannot create an instance fro% an
abstract class using t!e ne, oerator/ but an
abstract class can be used as a data t#e.
T!erefore/ t!e follo,ing state%ent/ ,!ic!
creates an arra# ,!ose ele%ents are of
"eo%etricObject t#e/ is correct.
"eo%etricObject@A geo B ne, "eo%etricObject@14AC
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
11
T!e Abstract Calendar Class and Its
"regorianCalendar subclass

java.util.GregorianCalendar
8"regorianCalendar()
8"regorianCalendar(#ear6 int/
%ont!6 int/ da#OfMont!6 int)
8"regorianCalendar(#ear6 int/
%ont!6 int/ da#OfMont!6 int/
!our6int/ %inute6 int/ second6 int)

Constructs a "regorianCalendar for t!e current ti%e.
Constructs a "regorianCalendar for t!e secified #ear/ %ont!/ and da# of
%ont!.
Constructs a "regorianCalendar for t!e secified #ear/ %ont!/ da# of
%ont!/ !our/ %inute/ and second. T!e %ont! ara%eter is 45based/ t!at
is/ 4 is for Danuar#.

java.util.Calendar
7Calendar()
8get(field6 int)6 int
8set(field6 int/ value6 int)6 void
8set(#ear6 int/ %ont!6 int/
da#OfMont!6 int)6 void
8getActualMa+i%u%(field6 int)6 int
8add(field: int, amount: int): void
8getTi%e()6 java.util.2ate
8setTi%e(date6 java.util.2ate)6 void







Constructs a default calendar.
9eturns t!e value of t!e given calendar field.
0ets t!e given calendar to t!e secified value.
0ets t!e calendar ,it! t!e secified #ear/ %ont!/ and date. T!e %ont!
ara%eter is 45based/ t!at is/ 4 is for Danuar#.
9eturns t!e %a+i%u% value t!at t!e secified calendar field could !ave.
Adds or subtracts t!e secified a%ount of ti%e to t!e given calendar field.
9eturns a 2ate object reresenting t!is calendarEs ti%e value (%illion
second offset fro% t!e >ni+ eoc!).
0ets t!is calendarEs ti%e ,it! t!e given 2ate object.

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
12
T!e Abstract Calendar Class and Its
"regorianCalendar subclass
An instance of jaa.util.!ate represents a
specific instant in time with millisecond
precision. jaa.util.Calendar is an abstract
base class for e"tracting detailed information
such as year# month# date# hour# minute and
second from a !ate object. $ubclasses of
Calendar can implement specific calendar
systems such as Gregorian calendar# %unar
Calendar and &ewish calendar. Currently#
jaa.util.GregorianCalendar for the Gregorian
calendar is supported in the &aa A'I.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
13
T!e "regorianCalendar Class
You can use new GregorianCalendar() to
construct a default GregorianCalendar with the
current time and use new
GregorianCalendar(year# month# date) to
construct a GregorianCalendar with the
specified year# month# and date. *he month
parameter is +,based# i.e.# + is for &anuary.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1$
T!e get Met!od in Calendar Class
*he get(int field) method defined in the
Calendar class is useful to e"tract the date and
time information from a Calendar object. *he
fields are defined as constants# as shown in
*able --.-.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1&
"etting 2ateFTi%e Infor%ation fro%
Calendar
TestCalendar
TestCalendar
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1(
Interfaces
.hat is an interface?
.hy is an interface useful?
/ow do you define an interface?
/ow do you use an interface?
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1*
:!at is an interfaceG
:!# is an interface usefulG
An interface is a classlike construct that
contains only constants and abstract methods.
In many ways# an interface is similar to an
abstract class# but the intent of an interface
is to specify properties for objects. 0or
e"ample# you can specify that the objects are
comparable# edible# cloneable using
appropriate interfaces.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
1-
2efine an Interface
*o distinguish an interface from a class# &aa
uses the following synta" to declare an interface1
public interface Interface2ame 3
constant declarations4
method signatures4
5
H+a%le6
public interface 6dible 3
788 !escribe how to eat 87
public abstract $tring how*o6at()4
5
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
13
Interface is a 0ecial Class
An interface is treated like a special class
in &aa. 6ach interface is compiled into a
separate bytecode file# just like a regular
class. %ike an abstract class# you cannot
create an instance from an interface using the
new operator# but in most cases you can use an
interface more or less the same way you use an
abstract class. 0or e"ample# you can use an
interface as a data type for a ariable# as
the result of casting# and so on.
TestInterface
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
24
H+a%le
You can now use the 6dible interface to
specify whether an object is edible. *his
is accomplished by letting the class for
the object implement this interface using
the implements keyword. 0or e"ample# the
classes Chicken and 0ruit in %isting --.9
implement the 6dible interface.
TestEdible
TestEdible
Edible
Edible
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
21
O%itting Modifiers in Interfaces
All data fields are public final static and all %et!ods are public
abstract in an interface. 1or t!is reason/ t!ese %odifiers can be
o%itted/ as s!o,n belo,6

public interface *- 3
public static final int : ; -4

public abstract oid p()4
5

HIuivalent
public interface *- 3
int : ; -4

oid p()4
5
A constant defined in an interface can be accessed using s#nta+
InterfaceJa%e.COJ0TAJTKJAMH (e.g./ T1.L).
TestInterface
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
22
H+a%le6 T!e Co%arable Interface
77 *his interface is defined in
77 jaa.lang package
package jaa.lang4
public interface Comparable 3
public int compare*o(<bject o)4
5
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
23
0tring and 2ate Classes
=any classes (e.g.# $tring and !ate) in the
&aa library implement Comparable to define a
natural order for the objects. If you e"amine
the source code of these classes# you will
see the keyword implements used in the
classes# as shown below1

public class $tring e"tends <bject
implements Comparable 3
77 class body omitted
5

public class !ate e"tends <bject
implements Comparable 3
77 class body omitted
5

new $tring() instanceof $tring
new $tring() instanceof Comparable
new jaa.util.!ate() instanceof jaa.util.!ate
new jaa.util.!ate() instanceof Comparable
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2$
"eneric ma" Met!od

77 =a".jaa1 0ind a ma"imum object
public class =a" 3
788 >eturn the ma"imum of two objects 87
public static <bject ma"
(<bject o-# <bject o?) 3
if (((Comparable)o-).compare*o(o?) @ +)
return o-4
else
return o?4
5
5


(a)

77 =a".jaa1 0ind a ma"imum object
public class =a" 3
788 >eturn the ma"imum of two objects 87
public static Comparable ma"
(Comparable o-# Comparable o?) 3
if (o-.compare*o(o?) @ +)
return o-4
else
return o?4
5
5

(b)


$tring s- ; AabcdefA4
$tring s? ; AabcdeeA4
$tring sB ; ($tring)=a".ma"(s-# s?)4

!ate d- ; new !ate()4
!ate d? ; new !ate()4
!ate dB ; (!ate)=a".ma"(d-# d?)4

*he return alue from the ma" method is of the
Comparable type. $o# you need to cast it to $tring or
!ate e"plicitly.
"enericMa+Test
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2&
2eclaring Classes to I%le%ent Co%arable
You cannot use the ma" method to find the larger of two instances of
>ectangle# because >ectangle does not implement Comparable. /oweer#
you can declare a new rectangle class that implements Comparable.
*he instances of this new class are comparable. %et this new class
be named Comparable>ectangle.
ComparableRectangle
ComparableRectangle
Co%arable9ectangle rectangle1 B ne, Co%arable9ectangle($/ &)C
Co%arable9ectangle rectangle2 B ne, Co%arable9ectangle(3/ ()C
0#ste%.out.rintln(Ma+.%a+(rectangle1/ rectangle2))C

9ectangle
5

GeometricObject
5
MinterfaceN
java.lang.Comparable

+compareo(o: Object): int
!otation:
"e interface name and t"e
met"od names are italici#ed.
"e das"ed lines and "ollo$
triangles are used to point to
t"e interface.
Co%arable9ectangle
5

Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2(
T!e Action%istener Interfaces

HandleEvent
HandleEvent
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
2*
;andling ">I Hvents
$ource object (e.g.# button)
%istener object contains a
method for processing the
eent.
ublic interface Action'istener O
ublic abstract void action=erfor%ed( ActionHvent e )C
P
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
;andling Hvent
!
$ource object keeps a list of listener
objects that implement Action%istener
!
Add a listener object to the list by
calling the
addAction%istener(Action%istener)
method of the source object.
!
Upon occurrence of an Action6ent
event at the source object1
Q
for eac! listener object listener in t!e list
N
DRM calls listener.action=erfor%ed( event )
2-
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
23
Trace H+ecution
ublic class ;andleHvent e+tends D1ra%e O
ublic ;andleHvent() O
S
FF OL'istenerClass listener1 B ne, OL'istenerClass()C
jbtOL.addAction'istener(listener1)C
S
P

ublic static void %ain(0tring@A args) O
S
P
P
class OL'istenerClass i%le%ents Action'istener O
ublic void action=erfor%ed(ActionHvent e) O
0#ste%.out.rintln(TOL button clic)edT)C
P
P
1. 0tart fro% t!e %ain
%et!od to create a
,indo, and disla#
it
animation
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
34
Trace H+ecution
ublic class ;andleHvent e+tends D1ra%e O
ublic ;andleHvent() O
S
OL'istenerClass listener1 B ne, OL'istenerClass()C
jbtOL.addAction'istener(listener1)C
S
P

ublic static void %ain(0tring@A args) O
S
P
P
class OL'istenerClass i%le%ents Action'istener O
ublic void action=erfor%ed(ActionHvent e) O
0#ste%.out.rintln(TOL button clic)edT)C
P
P
animation
2. Clic) OL
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
31
Trace H+ecution
ublic class ;andleHvent e+tends D1ra%e O
ublic ;andleHvent() O
S
OL'istenerClass listener1 B ne, OL'istenerClass()C
jbtOL.addAction'istener(listener1)C
S
P

ublic static void %ain(0tring@A args) O
S
P
P
class OL'istenerClass i%le%ents Action'istener O
ublic void action=erfor%ed(ActionHvent e) O
0#ste%.out.rintln(TOL button clic)edT)C
P
P
animation
3. Clic) OL. T!e
DRM invo)es t!e
listenerEs
action=erfor%ed
%et!od
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
32
T!e Cloneable Interfaces
package jaa.lang4
public interface Cloneable 3
5
Mar)er Interface6 An e%t# interface.
A %ar)er interface does not contain constants or %et!ods.
It is used to denote t!at a class ossesses certain desirable
roerties. A class t!at i%le%ents t!e Cloneable
interface is %ar)ed cloneable/ and its objects can be
cloned using t!e clone() %et!od defined in t!e Object
class.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
33
H+a%les
=any classes (e.g.# !ate and Calendar) in the &aa
library implement Cloneable. *hus# the instances
of these classes can be cloned. 0or e"ample# the
following code
Calendar calendar ; new GregorianCalendar(?++B# ?# -)4
Calendar calendarCopy ; (Calendar)calendar.clone()4
$ystem.out.println(Acalendar ;; calendarCopy is A C
(calendar ;; calendarCopy))4
$ystem.out.println(Acalendar.eDuals(calendarCopy) is A C
calendar.eDuals(calendarCopy))4

displays
calendar BB calendarCo# is false
calendar.eIuals(calendarCo#) is true
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3$
I%le%enting Cloneable Interface
*o declare a custom class that
implements the Cloneable interface#
the class must oerride the clone()
method in the <bject class. *he
following code declares a class named
/ouse that implements Cloneable and
Comparable.
House
House
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3&
0!allo, vs. 2ee Co#

!ouse16 ;ouse

id B 1
area B 1*&4.&4
,!en.uilt

1
Me%or#
,!en.uilt6 2ate

date object contents
!ouse2 B !ouse1.clone()
1*&4.&4
reference
!ouse26 ;ouse

id B 1
area B 1*&4.&4
,!en.uilt

1
Me%or#
1*&4.&4
reference
;ouse !ouse1 B ne, ;ouse(1/ 1*&4.&4)C
;ouse !ouse2 B (;ouse)!ouse1.clone()C
CloneH+a%le
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3(
Interfaces vs. Abstract Classes
In an interface/ t!e data %ust be constantsC an abstract class can
!ave all t#es of data.
Hac! %et!od in an interface !as onl# a signature ,it!out
i%le%entationC an abstract class can !ave concrete %et!ods.
Rariables Constructors Met!ods
Abstract
class
Jo restrictions Constructors are invo)ed b# subclasses
t!roug! constructor c!aining. An abstract
class cannot be instantiated using t!e ne,
oerator.
Jo restrictions.
Interface All variables
%ust be ublic
static final
Jo constructors. An interface cannot be
instantiated using t!e ne, oerator.
All %et!ods %ust be
ublic abstract
instance %et!ods
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3*
Interfaces vs. Abstract Classes/ cont.

Object Class%
&nterface% &nterface%'%
&nterface%'(
Class2
&nterface('%
&nterface('(
0uose t!at c is an instance of Class2. c is also an instance of Object/ Class1/
Interface1/ Interface1K1/ Interface1K2/ Interface2K1/ and Interface2K2.
All classes s!are a single root/ t!e Object class/ but t!ere is no single root for
interfaces. 'i)e a class/ an interface also defines a t#e. A variable of an interface
t#e can reference an# instance of t!e class t!at i%le%ents t!e interface. If a class
e+tends an interface/ t!is interface la#s t!e sa%e role as a suerclass. ?ou can use
an interface as a data t#e and cast a variable of an interface t#e to its subclass/
and vice versa.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
3-
Caution6 conflicting interfaces
In rare occasions/ a class %a# i%le%ent t,o interfaces
,it! conflict infor%ation (e.g./ t,o sa%e constants ,it!
different values or t,o %et!ods ,it! sa%e signature but
different return t#e). T!is t#e of errors ,ill be detected
b# t!e co%iler.
TestInterface
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
33
:!et!er to use an interface or a classG
Abstract classes and interfaces can bot! be used to %odel co%%on
features. ;o, do #ou decide ,!et!er to use an interface or a classG
In general/ a strong is5a relations!i t!at clearl# describes a
arent5c!ild relations!i s!ould be %odeled using classes. 1or
e+a%le/ a staff %e%ber is a erson. 0o t!eir relations!i s!ould be
%odeled using class in!eritance. A ,ea) is5a relations!i/ also
)no,n as an is5)ind5of relations!i/ indicates t!at an object
ossesses a certain roert#. A ,ea) is5a relations!i can be
%odeled using interfaces. 1or e+a%le/ all strings are co%arable/
so t!e 0tring class i%le%ents t!e Co%arable interface. ?ou can
also use interfaces to circu%vent single in!eritance restriction if
%ultile in!eritance is desired. In t!e case of %ultile in!eritance/
#ou !ave to design one as a suerclass/ and ot!ers as interface.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
Abstract Class vs Interface
!
$trong I$,A relation Abstract Class
Q
9ectangle is a GeometricObject
Q
Circle is a GeometricObject
!
'roperties7Capabilities Interface
Q
9ectangles are comparable b# areas
Q
9ectangles are cloneable
Q
9ectangles are seriali#able
Q
9ectangles can be colored
Q
9ectangles !ave perimeters
$4
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$1
:raer Classes
!
Eoolean
!
Character
!
$hort
!
Eyte
!
Integer
!
'ong
!
1loat
!
2ouble

java.lang.Object
5
2ouble
5
1loat
5
'ong
5
Integer
5
0!ort
5
.#te
5
C!aracter
5
.oolean
5
!umber
5
java.lang.Comparable
5
JOTH6 (1) T!e ,raer classes do
not !ave no5arg constructors. (2)
T!e instances of all ,raer
classes are i%%utable/ i.e./ t!eir
internal values cannot be c!anged
once t!e objects are created.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$2
T!e to0tring/ eIuals/ and !as!Code
Met!ods
6ach wrapper class oerrides the
to$tring# eDuals# and hashCode
methods defined in the <bject
class. $ince all the numeric
wrapper classes and the Character
class implement the Comparable
interface# the compare*o method
is implemented in these classes.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$3
T!e Ju%ber Class
6ach numeric wrapper class e"tends the
abstract 2umber class# which contains
the methods doubleFalue# floatFalue#
intFalue# longFalue# shortFalue# and
byteFalue. *hese methods GconertH
objects into primitie type alues.
*he methods doubleFalue# floatFalue#
intFalue# longFalue are abstract. *he
methods byteFalue and shortFalue are
not abstract# which simply return
(byte)intFalue() and
(short)intFalue()# respectiely.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$$
T!e Integer and !ouble Classes

java.lang.Integer
5value6 int
8MAUKRA'>H6 int
8MIJKRA'>H6 int

8Integer(value6 int)
8Integer(s6 0tring)
8valueOf(s6 0tring)6 Integer
8valueOf(s6 0tring/ radi+6 int)6 Integer
8arseInt(s6 0tring)6 int
8arseInt(s6 0tring/ radi+6 int)6 int

java.lang.!umber

8b#teRalue()6 b#te
8s!ortRalue()6 s!ort
8int)alue(): int
8long)laue(): long
8float)alue(): float
8double)alue():double

java.lang.2ouble
5value6 double
8MAUKRA'>H6 double
8MIJKRA'>H6 double

82ouble(value6 double)
82ouble(s6 0tring)
8valueOf(s6 0tring)6 2ouble
8valueOf(s6 0tring/ radi+6 int)6 2ouble
8arse2ouble(s6 0tring)6 double
8arse2ouble (s6 0tring/ radi+6 int)6 double

java.lang.Comparable

8compareo(o: Object): int
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$&
T!e Integer Class
and t!e !ouble Class
!
Constructors
!
Class Constants =AIJFA%U6#
=I2JFA%U6
!
Conersion =ethods
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$(
Ju%eric :raer Class Constructors
You can construct a wrapper object either
from a primitie data type alue or from a
string representing the numeric alue. *he
constructors for Integer and !ouble are1
ublic Integer(int value)
ublic Integer(0tring s)
ublic 2ouble(double value)
ublic 2ouble(0tring s)
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$*
Ju%eric :raer Class Constants
6ach numerical wrapper class has the
constants =AIJFA%U6 and =I2JFA%U6. =AIJFA%U6
represents the ma"imum alue of the
corresponding primitie data type. 0or Eyte#
$hort# Integer# and %ong# =I2JFA%U6
represents the minimum byte# short# int# and
long alues. 0or 0loat and !ouble# =I2JFA%U6
represents the minimum positive float and
double alues. *he following statements
display the ma"imum integer (?#-KL#KMB#NKL)#
the minimum positie float (-.K6,K9)# and
the ma"imum double floating,point number
(-.LOLNOB-BKMN?B-9L+eCB+Md).
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$-
Conversion Met!ods
6ach numeric wrapper class
implements the abstract
methods doubleFalue#
floatFalue# intFalue#
longFalue# and shortFalue#
which are defined in the
2umber class. *hese methods
GconertH objects into
primitie type alues.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
$3
T!e 0tatic valueOf Met!ods
*he numeric wrapper classes hae
a useful class method#
alue<f($tring s). *his method
creates a new object initialiPed
to the alue represented by the
specified string. 0or e"ample1

2ouble doubleObject B 2ouble.valueOf(T12.$T)C
Integer integerObject B Integer.valueOf(T12T)C
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&4
T!e Met!ods for =arsing 0trings into
Ju%bers
You hae used the parseInt method
in the Integer class to parse a
numeric string into an int alue
and the parse!ouble method in the
!ouble class to parse a numeric
string into a double alue. 6ach
numeric wrapper class has two
oerloaded parsing methods to
parse a numeric string into an
appropriate numeric alue.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&1
0orting an Arra# of Objects
<bjectie1 *he e"ample presents a generic
method for sorting an array of objects. *he
objects are instances of the Comparable
interface and they are compared using the
compare*o method.
GenericSort
GenericSort
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&2
TI=
&aa proides a static sort method for
sorting an array of <bject in the
jaa.util.Arrays class. $o you can use the
following code to sort arrays in this
e"ample1
java.util.Arra#s.sort(intArra#)C
java.util.Arra#s.sort(doubleArra#)C
java.util.Arra#s.sort(c!arArra#)C
java.util.Arra#s.sort(stringArra#)C
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&3
JOTH
Arrays are objects. An array is an instance
of the <bject class. 0urthermore# if A is a
subclass of E# eery instance of AQR is an
instance of EQR. *herefore# the following
statements are all true1
ne, int@14A instanceof Object
ne, "regorianCalendar@14A instanceof Calendar@AC
ne, Calendar@14A instanceof Object@A
ne, Calendar@14A instanceof Object
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&$
CA>TIOJ
Although an int alue can be assigned to a
double type ariable# intQR and doubleQR are
two incompatible types. *herefore# you cannot
assign an intQR array to a ariable of
doubleQR or <bjectQR type.
Liang, Introduction to Java Programming, Pearson Education, Inc. All rights reserved.
Adapted by S.C. Cheung
&&
Automatic Conersion Eetween 'rimitie
*ypes and .rapper Class *ypes
&!: -.9 allows primitie type and wrapper classes to be conerted automatically.
0or e"ample# the following statement in (a) can be simplified as in (b)1

IntegerQR intArray ; 3new Integer(?)#
new Integer(K)# new Integer(B)54

(a)
HIuivalent
(b)
IntegerQR intArray ; 3?# K# B54


Je, D2L 1.& bo+ing
Integer@A intArra# B O1/ 2/ 3PC
0#ste%.out.rintln(intArra#@4A 8 intArra#@1A 8 intArra#@2A)C
>nbo+ing
CSIT5100
Software Testing -
Overview
S.C. Cheung
HKUST
Slides adapted from www.introsoftwaretesting.com by Paul Ammann & eff
!ffutt
May 8, 2014 CSIT5100 2
Here! TestThis!
A stack of computer printoutsand no documentation
May 8, 2014 CSIT5100
There are 10 There are 10
14 14
possible paths! possible paths!
It would take It would take 3,170 years 3,170 years to to
exhaustively test the program exhaustively test the program
if eah test re!uires 1 ms!! if eah test re!uires 1 ms!!
!H" is Testing Cha##enging$
How long would it take
How long would it take
to exhaustively test this
to exhaustively test this
program?
program?
loop < 20 times
May 8, 2014 CSIT5100 4
Cost of Testing

I" real#world usage, testi"g is


I" real#world usage, testi"g is
the pri"iple post#desig" ativity
the pri"iple post#desig" ativity

$estriti"g early testi"g usually


$estriti"g early testi"g usually
i"reases ost
i"reases ost

%xte"sive hardware#software
%xte"sive hardware#software
i"tegratio" re!uires more testi"g
i"tegratio" re!uires more testi"g
Youre going to spend about half of
Youre going to spend about half of
your development budget on testing,
your development budget on testing,
whether you want to or not.
whether you want to or not.
May 8, 2014 CSIT5100 5
Mi%rosoft &'(#ishes !in)ows
*& +'g ,ist!!

&irosoft today published the full bug list for its &irosoft today published the full bug list for its
'i"dows () operati"g system* +or the first time ever, 'i"dows () operati"g system* +or the first time ever,
all k"ow" a"d reported bugs are to be made available all k"ow" a"d reported bugs are to be made available
to the publi* to the publi*

&r* ,ya"#-ee of .orea /photographed above0 made the &r* ,ya"#-ee of .orea /photographed above0 made the
mistake of pri"ti"g the whole list 11* mistake of pri"ti"g the whole list 11*
May 8, 2014 CSIT5100 -
In%i)ents of Software .ai#'res

2ria"e 3 Its maide" flight o" 4u"e 4, 1556 e"ded i" the lau"her bei"g 2ria"e 3 Its maide" flight o" 4u"e 4, 1556 e"ded i" the lau"her bei"g
exploded beause of a hai" of software failures exploded beause of a hai" of software failures

-o"do" 2mbula"e 7eause of a suessio" of software e"gi"eeri"g -o"do" 2mbula"e 7eause of a suessio" of software e"gi"eeri"g
failures, espeially defets i" pro8et ma"ageme"t, a system was failures, espeially defets i" pro8et ma"ageme"t, a system was
i"trodued that failed twie i" the autum" of 1559* 2lthough the i"trodued that failed twie i" the autum" of 1559* 2lthough the
mo"etary ost, at :o"ly; about <5m, was small by ompariso" with other mo"etary ost, at :o"ly; about <5m, was small by ompariso" with other
examples, it is believed that people died who would "ot have died if examples, it is believed that people died who would "ot have died if
ambula"es had reahed them as promptly as they would have do"e ambula"es had reahed them as promptly as they would have do"e
without this software failure* without this software failure*

Thera#93 7etwee" 15=3 a"d 15=7 six people /at least0 suffered serious Thera#93 7etwee" 15=3 a"d 15=7 six people /at least0 suffered serious
radiatio" overdoses beause of software#related malfu"tio"s of the radiatio" overdoses beause of software#related malfu"tio"s of the
Thera#93 radiatio" therapy mahi"e* Three of them are thought to have Thera#93 radiatio" therapy mahi"e* Three of them are thought to have
died of the overdoses* 2" importa"t root ause was a lak of !uality died of the overdoses* 2" importa"t root ause was a lak of !uality
assura"e, whih led to a" over#omplex, i"ade!uately tested, assura"e, whih led to a" over#omplex, i"ade!uately tested,
u"der#doume"ted system bei"g developed, a"d subse!ue"tly to the u"der#doume"ted system bei"g developed, a"d subse!ue"tly to the
failure to take ade!uate orretive atio"* failure to take ade!uate orretive atio"*

-o"do" >tok %xha"ge Taurus was a pla""ed automated tra"satio" -o"do" >tok %xha"ge Taurus was a pla""ed automated tra"satio"
settleme"t system* The pro8et was a"eled i" 1553 after havi"g settleme"t system* The pro8et was a"eled i" 1553 after havi"g
lasted more tha" five years a"d osti"g arou"d <73m? the estimated lasted more tha" five years a"d osti"g arou"d <73m? the estimated
loss to ustomers was arou"d <430m? a"d the damage to the reputatio" loss to ustomers was arou"d <430m? a"d the damage to the reputatio"
of the -o"do" >tok %xha"ge was i"alulable* of the -o"do" >tok %xha"ge was i"alulable*
May 8, 2014 CSIT5100 /
0n In%i)ent in Hong 1ong

,ow about our +>@As Third Be"eratio"


,ow about our +>@As Third Be"eratio"
&obiliCi"g >ystem lau"hed i" 9003D /
&obiliCi"g >ystem lau"hed i" 9003D /
httpEFFwww*i"fo*gov*hkFgiaFge"eralF900
httpEFFwww*i"fo*gov*hkFgiaFge"eralF900
304F97F04970170*htm
304F97F04970170*htm
0
0
May 8, 2014 CSIT5100 8
Testing in the 21st Cent'ry

'e are goi"g through a time of ha"ge 'e are goi"g through a time of ha"ge

>oftware defi"es behavior >oftware defi"es behavior

networ" routers

financial networ"s

telephone switching networ"s

other infrastructure

%mbedded Go"trol 2ppliatio"s %mbedded Go"trol 2ppliatio"s

airplanes

#$%& systems

Sensor'enabled systems

Cellular phones

>afety ritial, real#time software >afety ritial, real#time software

2"d of ourse 1 'e wa"t 'hatsapp a"d Ga"dy Gru"h 2"d of ourse 1 'e wa"t 'hatsapp a"d Ga"dy Gru"h
"ot to rash i" the middle! "ot to rash i" the middle!
Testing ideas have
Testing ideas have
matured enough to
matured enough to
be used in practice
be used in practice
May 8, 2014 CSIT5100 2
Software )eve#o34ent a%tivities
an) testing #eve#s
May 8, 2014 CSIT5100 10
I43ortant Ter4s
5a#i)ation 6 5eri7%ation

Halidatio" E The proess of evaluati"g Halidatio" E The proess of evaluati"g


software at the e"d of software developme"t software at the e"d of software developme"t
to e"sure omplia"e with i"te"ded usage to e"sure omplia"e with i"te"ded usage

Herifiatio" E The proess of determi"i"g Herifiatio" E The proess of determi"i"g


whether the produts of a give" phase of the whether the produts of a give" phase of the
software developme"t proess fulfill the software developme"t proess fulfill the
re!uireme"ts established duri"g the previous re!uireme"ts established duri"g the previous
phase phase

IHIH sta"ds for :i"depe"de"t verifiatio" IHIH sta"ds for :i"depe"de"t verifiatio"
a"d validatio"; a"d validatio";
May 8, 2014 CSIT5100 11
Stati% an) 8yna4i% Testing

>tati Testi"g
>tati Testi"g
E Testi"g without
E Testi"g without
exeuti"g the program*
exeuti"g the program*

This include software inspections and some forms of


analyses.

@y"ami Testi"g
@y"ami Testi"g
E Testi"g by exeuti"g
E Testi"g by exeuti"g
the program with real i"puts
the program with real i"puts
May 8, 2014 CSIT5100 12
Software .a'#ts, 9rrors 6
.ai#'res

>oftware +ault >oftware +ault E E 2 stati defet i" the software 2 stati defet i" the software

>oftware %rror >oftware %rror E 2" i"orret i"ter"al state E 2" i"orret i"ter"al state
that is the ma"ifestatio" of some fault that is the ma"ifestatio" of some fault

>oftware +ailure >oftware +ailure E %xter"al, i"orret behavior E %xter"al, i"orret behavior
with respet to the re!uireme"ts or other with respet to the re!uireme"ts or other
desriptio" of the expeted behavior desriptio" of the expeted behavior
Faults in software are design mistakes and will always exist Faults in software are design mistakes and will always exist
May 8, 2014 CSIT5100 1
I##'strative 9:a43#e
publi stati i"t "umJero /i"tKL x0 M publi stati i"t "umJero /i"tKL x0 M
FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio" FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio"
FF else retur" the "umber of ourre"es of 0 i" x FF else retur" the "umber of ourre"es of 0 i" x
i"t ou"t N 0? i"t ou"t N 0?
for /i"t i N 1? i P x*le"gth? iQQ0 M for /i"t i N 1? i P x*le"gth? iQQ0 M
if /xKiL NN 00 M if /xKiL NN 00 M
ou"tQQ? ou"tQQ?
R R
R R
retur" ou"t? retur" ou"t?
R R
May 8, 2014 CSIT5100 14
I##'strative 9:a43#e ;
Software .a'#t
publi stati i"t "umJero /i"tKL x0 M publi stati i"t "umJero /i"tKL x0 M
FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio" FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio"
FF else retur" the "umber of ourre"es of 0 i" x FF else retur" the "umber of ourre"es of 0 i" x
i"t ou"t N 0? i"t ou"t N 0?
for /i"t i N for /i"t i N 1 1? i P x*le"gth? iQQ0 M ? i P x*le"gth? iQQ0 M
if /xKiL NN 00 M if /xKiL NN 00 M
ou"tQQ? ou"tQQ?
R R
R R
retur" ou"t? retur" ou"t?
R R
May 8, 2014 CSIT5100 15
I##'strative 9:a43#e ;
Software 9rror
publi stati i"t "umJero /i"tKL x0 M publi stati i"t "umJero /i"tKL x0 M
FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio" FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio"
FF else retur" the "umber of ourre"es of 0 i" x FF else retur" the "umber of ourre"es of 0 i" x
i"t ou"t N 0? i"t ou"t N 0?
for /i"t i N for /i"t i N 1 1? i P x*le"gth? iQQ0 M ? i P x*le"gth? iQQ0 M
if /xKiL NN 00 M if /xKiL NN 00 M
ou"tQQ? ou"tQQ?
R R
R R
retur" ou"t? retur" ou"t?
R R
numZero([2, 7, 0])
Any failure occur
Any error occur
May 8, 2014 CSIT5100 1-
I##'strative 9:a43#e ;
Software 9rror
publi stati i"t "umJero /i"tKL x0 M publi stati i"t "umJero /i"tKL x0 M
FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio" FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio"
FF else retur" the "umber of ourre"es of 0 i" x FF else retur" the "umber of ourre"es of 0 i" x
i"t ou"t N 0? i"t ou"t N 0?
for /i"t i N for /i"t i N 1 1? i P x*le"gth? iQQ0 M ? i P x*le"gth? iQQ0 M
if /xKiL NN 00 M if /xKiL NN 00 M
ou"tQQ? ou"tQQ?
R R
R R
retur" ou"t? retur" ou"t?
R R
numZero([2, 7, 0])
Any failure occur
Any error occur
!tate error occurs at t"e first iteration w"ere t"e state is (x#[2,7,0],
count#0, i#$, %&#if)' ("e correct state s"ould )e (x#[2,7,0], count#0,
i#0, %&#if)'
May 8, 2014 CSIT5100 1/
I##'strative 9:a43#e ;
Software 9rror
publi stati i"t "umJero /i"tKL x0 M publi stati i"t "umJero /i"tKL x0 M
FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio" FF %ffetsE if x NN "ull throw Oull)oi"ter%xeptio"
FF else retur" the "umber of ourre"es of 0 i" x FF else retur" the "umber of ourre"es of 0 i" x
i"t ou"t N 0? i"t ou"t N 0?
for /i"t i N for /i"t i N 1 1? i P x*le"gth? iQQ0 M ? i P x*le"gth? iQQ0 M
if /xKiL NN 00 M if /xKiL NN 00 M
ou"tQQ? ou"tQQ?
R R
R R
retur" ou"t? retur" ou"t?
R R
numZero([0, 7, 2])
Any failure occur
Any error occur
Can yo' thin< of a 3rogra4
e:a43#e an) a test %ase that
triggers a fa'#t ('t %a'ses no error
an) fai#'re$
May 8, 2014 CSIT5100 18
int s*uare (int x) +
int result # x , x-
return result-
.
(est case/ s*uare(2)
May 8, 2014 CSIT5100 12
Testing 6 8e('gging

Testi"g
Testi"g
E +i"di"g i"puts that ause
E +i"di"g i"puts that ause
the software to fail
the software to fail

@ebuggi"g
@ebuggi"g
E The proess of fi"di"g a
E The proess of fi"di"g a
fault give" a failure
fault give" a failure
May 8, 2014 CSIT5100 20
.a'#t 6 .ai#'re Mo)e#
Three o"ditio"s "eessary for a failure
Three o"ditio"s "eessary for a failure
to our
to our
1* 1*
$eahability
$eahability
E The loatio" or
E The loatio" or
loatio"s i" the program that o"tai"
loatio"s i" the program that o"tai"
the fault must be reahed
the fault must be reahed
9* 9*
I"fetio"
I"fetio"
E The state of the program
E The state of the program
must be i"orret
must be i"orret
3* 3*
)ropagatio"
)ropagatio"
E The i"feted state must
E The i"feted state must
propagate to ause some output of the
propagate to ause some output of the
program to be i"orret
program to be i"orret
May 8, 2014 CSIT5100 21
Test Case =>Test Case 5a#'es ?
9:3e%te) @es'#tsA

Test Gase Halues Test Gase Halues E The i"put values E The i"put values
"eessary to omplete the i"te"ded "eessary to omplete the i"te"ded
program exeutio" of a test ase* program exeutio" of a test ase*

%xpeted $esults %xpeted $esults E The result that will E The result that will
be produed whe" exeuti"g the test if be produed whe" exeuti"g the test if
the program satisfies its i"te"ded the program satisfies its i"te"ded
behavior* behavior*

Test >et Test >et E 2 set of test ases* E 2 set of test ases*

Test >ript Test >ript E 2 test ase that is E 2 test ase that is
prepared i" a form for automati prepared i" a form for automati
exeutio"* exeutio"*
May 8, 2014 CSIT5100 22
O(serva(i#ity an)
Contro##a(i#ity

>oftware Sbservability >oftware Sbservability E ,ow easy it is to E ,ow easy it is to


observe the program behavior i" terms of its observe the program behavior i" terms of its
outputs, effets o" the e"viro"me"t a"d outputs, effets o" the e"viro"me"t a"d
other hwFsw ompo"e"ts other hwFsw ompo"e"ts

Software that affects hardware de(ices) databases) or remote files


ha(e low obser(ability

>oftware Go"trollability >oftware Go"trollability E ,ow easy it is to E ,ow easy it is to


provide a program with the "eeded i"puts, i" provide a program with the "eeded i"puts, i"
terms of values, operatio"s, a"d behaviors terms of values, operatio"s, a"d behaviors

*asy to control software with inputs from "eyboards+mouse

%nputs from hw sensors or distributed software is harder

&ata abstraction reduces controllability and obser(ability ,e.g.) preset


scenes of digital cameras-
May 8, 2014 CSIT5100 2
To3-8own an) +otto4-B3
Testing

Top#@ow" Testi"g
Top#@ow" Testi"g
E Test the
E Test the
mai" proedure, the" go dow"
mai" proedure, the" go dow"
through proedures it alls
through proedures it alls

7ottom#Tp Testi"g
7ottom#Tp Testi"g
E Test the leaves i"
E Test the leaves i"
the tree /proedures that make "o
the tree /proedures that make "o
alls0, a"d move up to the root*
alls0, a"d move up to the root*

*ach procedure is not tested until all of its children ha(e


been tested
May 8, 2014 CSIT5100 24
!hite-(o: an) +#a%<-(o:
Testing

7lak#box testi"g 7lak#box testi"g E @erivi"g tests from E @erivi"g tests from
exter"al desriptio"s of the software, exter"al desriptio"s of the software,
i"ludi"g speifiatio"s, re!uireme"ts, a"d i"ludi"g speifiatio"s, re!uireme"ts, a"d
desig" desig"

'hite#box testi"g 'hite#box testi"g E @erivi"g tests from the E @erivi"g tests from the
soure ode i"ter"als of the software, soure ode i"ter"als of the software,
speifially i"ludi"g bra"hes, i"dividual speifially i"ludi"g bra"hes, i"dividual
o"ditio"s, a"d stateme"ts o"ditio"s, a"d stateme"ts
Alternati0e 0iew/ Alternati0e 0iew/ At which level of abstraction to derive tests At which level of abstraction to derive tests
May 8, 2014 CSIT5100 25
C#assi7%ation of Testing

Go"ve"tio"al lassifiatio" of Go"ve"tio"al lassifiatio" of


testi"g is to divide testi"g at testi"g is to divide testi"g at
speifi software developme"t speifi software developme"t phases phases

Unit) module) integration) system .

Oew lassifiatio" is i" terms of Oew lassifiatio" is i" terms of


strutures strutures a"d a"d riteria riteria

/raphs) logical e0pressions) synta0) input space


May 8, 2014 CSIT5100 2-
Conventiona# C Testing at
8iDerent ,eve#s
&lass A
met"od mA$()
met"od mA2()
&lass 1
met"od m1$()
met"od m12()
main &lass %
I
Acce2tance testing/ 3s
t"e software acce2ta)le
to t"e user
I
3ntegration testing/
(est "ow modules
interact wit" eac"
ot"er
I
!ystem testing/ (est t"e
o0erall functionality of
t"e system
I
4odule testing/ (est
eac" class, file, module
or com2onent
I
5nit testing/ (est eac"
unit (met"od)
indi0idually
May 8, 2014 CSIT5100 2/
Conventiona# C .in) a Era3h an)
Cover It

Tailored toE
Tailored toE

a particular software artifact

code) design) specifications

a particular phase of the lifecycle

re1uirements) specification) design) implementation

-imitatio"sE
-imitatio"sE

%t obscures underlying similarities

/raphs do not characteri2e all testing techni1ues well

+our abstrat models


+our abstrat models
suffie
suffie
May 8, 2014 CSIT5100 28
Test Coverage Criteria

Test $e!uireme"ts Test $e!uireme"ts E >peifi software eleme"ts E >peifi software eleme"ts
that a test ase must satisfy or over that a test ase must satisfy or over

Test Griterio" Test Griterio" E 2 olletio" of rules a"d a E 2 olletio" of rules a"d a
proess that defi"e test re!uireme"ts proess that defi"e test re!uireme"ts
A tester6s 7o) is sim2le / Define a model of the
software, then find ways
to cover it
(esting researc"ers "a0e defined do8ens of criteria, )ut t"ey (esting researc"ers "a0e defined do8ens of criteria, )ut t"ey
are all really 7ust a few criteria on four ty2es of structures 9 are all really 7ust a few criteria on four ty2es of structures 9
May 8, 2014 CSIT5100 22
Test Coverage Criteria =+ran%h
CoverageA

%ah outgoi"g edge %ah outgoi"g edge


of a deisio" "ode of a deisio" "ode
is a test is a test
re!uireme"t* re!uireme"t*

There are 19 test There are 19 test


re!uireme"ts* re!uireme"ts*

Griterio" that Griterio" that


imposes these 19 imposes these 19
test re!uireme"ts test re!uireme"ts
o" eah test set o" eah test set
is Ubra"h is Ubra"h
overageV* overageV*
Flow :ra2"
May 8, 2014 CSIT5100 0
Test Coverage Criteria =Ca##
CoverageA
&all :ra2"

%ah subrouti"e
%ah subrouti"e
i"voatio" is a
i"voatio" is a
test
test
re!uireme"t*
re!uireme"t*

Griterio" that
Griterio" that
imposes all
imposes all
these test
these test
re!uireme"ts o"
re!uireme"ts o"
a test set is
a test set is
Uall overageV*
Uall overageV*
May 8, 2014 CSIT5100 1
Test Coverage Criteria
=State4ent CoverageA

%ah stateme"t i"voatio" is a test


%ah stateme"t i"voatio" is a test
re!uireme"t*
re!uireme"t*

Griterio" imposes all these re!uireme"ts


Griterio" imposes all these re!uireme"ts
o" a test set is Ustateme"t overageV*
o" a test set is Ustateme"t overageV*
May 8, 2014 CSIT5100 2 32
Few C Criteria +ase) on
Str'%t'res
1* 1*
Braphs
Braphs
9* 9*
-ogial
-ogial
%xpressio"s
%xpressio"s
3* 3*
I"put @omai"
I"put @omai"
GharateriCatio
GharateriCatio
"
"
4* 4*
>y"tati
>y"tati
>trutures
>trutures
(not X or not Y) and A and B
if (x > y)
z = x - y;
else
z = 2 * x;
!tructures / Four ways to model software
A: {0, 1, >1}
B: {600, 700, 800}
C: {swe, cs, isa, infs}
May 8, 2014 CSIT5100 33
1G Era3h Coverage ;
Str'%t'ra#
;
<
=
2
$ 7
>
?ode (!tatement)
Cover every node

$2<;7

$=>=<;7
("is gra2" may re2resent
statements @ )ranc"es
met"ods @ calls
com2onents @ signals

states and transitions


Adge (1ranc")
Cover every edge

$2<;7

$=>=<7
%at"
Cover every path

$2<;7

$2<7

$=<;7

$=<7

$=>=<;7

$=>=<7 9
May 8, 2014 CSIT5100 4 34
Befs @ 5ses %airs
(x, $, ($,2)), (x, $, ($,=))

(y, $, >), (y, $, ;)


(a, 2, (<,;)), (a, 2, (<,7)), (a,
=, (<,;)), (a, =, (<,7)),
(m, >, 7), (m, ;, 7)
1G Era3h Coverage ; 8ata
.#ow
;
<
=
2
$ 7
>
("is gra2" contains/
defs/ nodes @ edges w"ere
0aria)les get 0alues
uses/ nodes @ edges w"ere
0alues are accessed
def = {x, y}
def = {a , m}
def = {a}
def = {m}
def = {m}
use = {x}
use = {x}
use = {a}
use = {a}
use = {y}
use = {m}
use = {y}
All Befs
Every def used once

$2<;7

$=>=<7
All 5ses
Every def reaches every
use

$2<;7

$2<7

$=<;7

$=<7

$=>=<7
May 8, 2014 CSIT5100 5 35
1G Era3h - .SM 9:a43#e
Me4ory Seats in a ,e:'s 9S
00
Bri0er $
&onfiguration
Bri0er 2
&onfiguration
[Ignition = off] | Button2
[Ignition = off] | Button1
4odified
&onfiguration
sideMirrors () [Ignition = on] |
lumbar () [Ignition = on] |
seatBottom () [Ignition = on] |
seatBack () [Ignition = on] |
?ew
&onfiguration
Bri0er $
?ew
&onfiguration
Bri0er 2
[Ignition = on] | Reset AND Button1
[Ignition = on] | Reset AND Button2
Ignition = off
Ignition = off
(to Modified)
:uard (safety constraint)
(rigger (in2ut)
May 8, 2014 CSIT5100 - 36
2G ,ogi%a# 9:3ressions
( (a > b) or G ) and (x < y)
(ransitions
!oftware !2ecifications
%rogram Becision !tatements
Cogical
Ax2ressions
May 8, 2014 CSIT5100 / 37
2G ,ogi%a# 9:3ressions

)rediate Goverage )rediate Goverage E %ah prediate must be E %ah prediate must be
true a"d false true a"d false

( (a>b) or G ) and (x < y) 3 True) $alse

Glause Goverage Glause Goverage E %ah lause must be true E %ah lause must be true
a"d false a"d false

(a > b) 3 True) $alse

G 3 True) $alse

(x < y) 3 True) $alse

Gombi"atorial Goverage Gombi"atorial Goverage E Harious ombi"atio"s E Harious ombi"atio"s


of lauses of lauses

Active Clause Coverage4 *ach clause must determine the predicate5s result
( (a > b) or G ) and (x < y)
May 8, 2014 CSIT5100 8
38
2G ,ogi% ; 0%tive C#a'se
Coverage
( (a > b) or G ) and (x < y)
1 T F T
2 F F T
du2licate
3 F T T
4 F F T
5 T T T
6 T T F
Dit" t"ese 0alues
for : and (xEy),
(aF)) determines
t"e 0alue of t"e
2redicate
May 8, 2014 CSIT5100 2
G In3't 8o4ain
Chara%teriHation

@esribe the
@esribe the
i"put domai"
i"put domai"
of the software
of the software

%dentify inputs) parameters) or other categori2ation

Partition each input into finite sets of representati(e (alues

Choose combinations of (alues

>ystem level
>ystem level

6umber of students 7 0, , > 8

9e(el of course 7 !00, "00, #00 8

:a;or 7 s$e, cs, isa, in%s 8

T"it level
T"it level

Parameters & (int ', int ()

Possible (alues <) * <0, 0, , +, >+ ,, ( ) * 0, +0, -0 ,

Tests

& (./, 0), & (0, +0), & (, -0), & (+, 0), & (/, +0)
May 8, 2014 CSIT5100 40
4G Synta%ti% Str'%t'res

7ased o" a
7ased o" a
grammar
grammar
, or other
, or other
sy"tati defi"itio"
sy"tati defi"itio"

)rimary example is
)rimary example is
mutatio" testi"g
mutatio" testi"g
=. %nduce small changes to the program4 mutants
>. $ind tests that cause the mutant programs to fail4 "illing
mutants
?. $ailure is defined as different output from the original program
@. Chec" the output of useful tests on the original program

%xample program a"d muta"ts


%xample program a"d muta"ts
if (x > y)
z = x - y;
else
z = 2 * x;
if (x > y)
if (x >= y)
z = x - y;
z = x + y;
z = x m;
else
z = 2 * x;
May 8, 2014 CSIT5100 41
Coverage Overview
Four Structures for
Four Structures for
Modeling Software
Modeling Software
Graphs
Graphs
Logic
Logic
nput Space
nput Space
Synta!
Synta!
"se cases "se cases
Specs Specs
#esign #esign
Source Source
$pplied
to
#%F #%F
Specs Specs
FSMs FSMs
Source Source
$pplied to
nput nput
Models Models
nteg nteg
Source Source
$pplied
to
May 8, 2014 CSIT5100 42
Coverage
:i0en a set of test re*uirements :i0en a set of test re*uirements TR TR for co0erage criterion for co0erage criterion
C C, a test set , a test set T T satisfies satisfies C C co0erage if and only if for e0ery co0erage if and only if for e0ery
test re*uirement test re*uirement tr tr in in TR TR, t"ere is at least one test , t"ere is at least one test t t in in T T
suc" t"at suc" t"at t t satisfies satisfies tr tr
!u22ose t"at (G consists
of fi0e test re*uirement,
eac" re2resented in a
different color'
(est set satisfies (G
May 8, 2014 CSIT5100 4
Coverage

I"feasible test re!uireme"ts I"feasible test re!uireme"ts E test E test


re!uireme"ts that a""ot be satisfied re!uireme"ts that a""ot be satisfied

6o test case (alues e0ist that meet the test re1uirements

&ead code

&etection of infeasible test re1uirements is formally undecidable


for most test criteria

Thus, 100W overage is Thus, 100W overage is impossible impossible i" i"
pratie pratie
!u22ose t"at (G consists
of fi0e test re*uirement,
eac" re2resented in a
different color'
May 8, 2014 CSIT5100 44
Two !ays to Bse Test Criteria
1* 1* @iretly ge"erate @iretly ge"erate test values test values to satisfy to satisfy the the
riterio" riterio"

!ften assumed by the research community

:ost ob(ious way to use criteria

Aery hard without automated tools


9* 9* Be"erate test values Be"erate test values exter"ally exter"ally a"d a"d measure measure
agai"st the riterio" usually favored by agai"st the riterio" usually favored by
i"dustry i"dustry

sometimes misleading

if tests do not reach =BBC co(erage) what does that meanD


Test riteria are sometimes alled Test riteria are sometimes alled metris metris
May 8, 2014 CSIT5100 45
Eenerators an) @e%ogniHers

Be"erator Be"erator E 2 proedure that automatially E 2 proedure that automatially


ge"erates values to satisfy a riterio" ge"erates values to satisfy a riterio"

$eog"iCer $eog"iCer E 2 proedure that deides E 2 proedure that deides


whether a give" set of test values satisfies whether a give" set of test values satisfies
a riterio" a riterio"

7oth problems are provably 7oth problems are provably u"deidable u"deidable for for
most riteria most riteria

It is possible to reog"iCe whether test It is possible to reog"iCe whether test


ases satisfy a riterio" far more ofte" ases satisfy a riterio" far more ofte"
tha" it is possible to ge"erate tests that tha" it is possible to ge"erate tests that
satisfy the riterio" satisfy the riterio"

Goverage a"alysis tools Goverage a"alysis tools are !uite ple"tiful are !uite ple"tiful
May 8, 2014 CSIT5100 4-
Co43aring Criteria with
S'(s'43tion

Griteria >ubsumptio" Griteria >ubsumptio" E 2 test riterio" E 2 test riterio"


C1 C1 subsumes subsumes C2 C2 if a"d o"ly if every set if a"d o"ly if every set
of test ases that satisfies riterio" of test ases that satisfies riterio" C1 C1
also satisfies also satisfies C2 C2

&ust be true for &ust be true for every set every set of test ases of test ases

Example Example E If a test set has overed every E If a test set has overed every
bra"h i" a program /satisfied the bra"h bra"h i" a program /satisfied the bra"h
riterio"0, the test set is guara"teed to riterio"0, the test set is guara"teed to
also have overed every stateme"t also have overed every stateme"t
May 8, 2014 CSIT5100 4/
Test Coverage Criteria

Traditio"al software testi"g is Traditio"al software testi"g is expe"sive expe"sive


a"d a"d labor#i"te"sive labor#i"te"sive

+ormal overage riteria are used to deide +ormal overage riteria are used to deide
whih test i"puts whih test i"puts to use to use

&ore likely that the tester will &ore likely that the tester will fi"d fi"d
problems problems

Breater assura"e that the software is of Breater assura"e that the software is of
high !uality high !uality a"d a"d reliability reliability

2 goal or 2 goal or stoppi"g rule stoppi"g rule for testi"g for testi"g

Griteria makes testi"g more Griteria makes testi"g more effiie"t effiie"t a"d a"d
effetive effetive
1ut "ow do we start to a22ly t"ese ideas in 2ractice
1ut "ow do we start to a22ly t"ese ideas in 2ractice
May 8, 2014 CSIT5100 48
S'44ary

&ore testi"g saves


&ore testi"g saves
mo"ey
mo"ey

Planning for testing sa(es lots of money

Testi"g is
Testi"g is
"o
"o
lo"ger
lo"ger
a" :art form;
a" :art form;

*ngineers ha(e a tool bo0 of test criteria

'he" testers beome


'he" testers beome
e"gi"eers
e"gi"eers
, the
, the
produt gets better
produt gets better

The de(elopers get better


May 8, 2014 CSIT5100 42
9:er%ise

>uppose that overage riterio" G1


>uppose that overage riterio" G1
subsumes riterio" G9* +urther suppose
subsumes riterio" G9* +urther suppose
that test set T1 satisfies G1 a"d test
that test set T1 satisfies G1 a"d test
set T9 satisfies G9 o" the same
set T9 satisfies G9 o" the same
program*
program*

&oes T= necessarily satisfy C>D

&oes T> necessarily satisfy C=D

%f T> re(eals a fault) does T= necessarily re(eal the faultD


May 8, 2014 CSIT5100 50 50
1G Era3h Coverage ;
Str'%t'ra#
;
<
=
2
$ 7
>
?ode (!tatement)
Cover every node

$2<;7

$=>=<;7
("is gra2" may re2resent
statements @ )ranc"es
met"ods @ calls
com2onents @ signals

states and transitions


Adge (1ranc")
Cover every edge

$2<;7

$=>=<7
%at"
Cover every path

$2<;7

$2<7

$=<;7

$=<7

$=>=<;7

$=>=<7 9
x # =-
x # 0-
y # H I x-
May 8, 2014 CSIT5100 51
Bn-assesse) Ho4ewor<

@o homework %xerise Test1 after


@o homework %xerise Test1 after
lass*
lass*

)lease do"Vt look at the solutio"


)lease do"Vt look at the solutio"
before tryi"g the problem yourself*
before tryi"g the problem yourself*
May 8, 2014 CSIT5100 52
O3en I'estions

'hih 'hih riteria riteria work best o" e"terprise, highly work best o" e"terprise, highly
reliable softwareD reliable softwareD

Ehich software structure to useD

,ow a" we best ,ow a" we best automate automate this testi"g with robust this testi"g with robust
toolsD toolsD

&eri(ing the software structure

Constructing the test re1uirements

Creating (alues from test re1uirements

Creating full test scripts

Solution to the Fmapping problemG

%mpirial %mpirial validatio" validatio"

Teh"ology Teh"ology tra"sitio" tra"sitio"

2ppliatio" to 2ppliatio" to "ew "ew domai"s domai"s


CSIT5100
Software Testing -
Graph Coverage
Criteria
S.C. Cheung
HKUST
Slides adapted from www.introsoftwaretesting.com by Paul Ammann & eff
!ffutt
May 8, 2014 CSIT5100 2
2
Graph Coverage
Four Structures for
Four Structures for
Modeling Software
Modeling Software
Graphs
Graphs
Logic
Logic
Input Space
Input Space
Syntax
Syntax
Use cases Use cases
Specs Specs
Design Design
Source Source
Applied
to
DNF DNF
Specs Specs
FSMs FSMs
Source Source
Applied to
Input Input
Models Models
Integ Integ
Source Source
Applied
to
May 8, 2014 CSIT5100 3
Covering Graphs

"raphs are the most commonly used structure for


testing

"raphs can come from many sources

Control flow graphs

#esign structure

$S%s and statecharts

Use cases

Tests usually are intended to &co'er( the graph in


some way
May 8, 2014 CSIT5100 4
e!nition of a Graph

A set N of nodes) N is not empty

A set N
0
of initial nodes) N
0
is not empty

A set N
f
of final nodes) N
f
is not empty

A set E of edges) each edge from one node to


another

* n
i
) n
j
+) i is predecessor) j is successor
May 8, 2014 CSIT5100 5
Three "#a$p%e Graphs
0
2 1
3
N
0
= { 0 }
N
f
= { 3 }
0
2 1
3
N
0
= { }
N
f
= { 3 }
9
0
4 3
7
1
5
8
2
6
N
0
= { 0, 1, 2 }
N
f
= { 7, 8, 9 }
Not a Not a
valid valid
graph graph
May 8, 2014 CSIT5100 &
'aths in Graphs

Path , A se-uence of nodes . /n


0
) n
1
) 2) n
%
3

4ach pair of nodes is an edge

5ength , The number of edges

A single node is a path of length 6

Subpath , A subse-uence of nodes in p is a subpath of p

7each *n+ , Subgraph that can be reached from n


9 7 8
0 1 2
4 3 5 6
Paths
[ 0, 3, 7
[ 1, 4, 8, 5, 1
[ 2, 6, 9
!"a#h $0% = { 0, 3, 4, 7,
8, 5, 1, 9 }
!"a#h ${0, 2}% = &
!"a#h$[2,6% = {2, 6, 9}
May 8, 2014 CSIT5100 (
Test 'aths an) S"S"s

Test Path , A path that starts at an initial node and ends


at a final node

Test paths represent e8ecution of test cases

Some test paths can be e8ecuted by many tests

Some test paths cannot be e8ecuted by any tests

S4S4 graphs , All test paths start at a single node and


end at another node

Single9entry) single9e8it

:o and :f ha'e e8actly one node


0
2
1
6 3
5
4
'o()l"*dia+o,d graph
-o(r t"st paths
[ 0, 1, 3, 4, 6
[ 0, 1, 3, 5, 6
[ 0, 2, 3, 4, 6
[ 0, 2, 3, 5, 6
May 8, 2014 CSIT5100 8
*isiting an) To+ring

;isit , A test path p visits node n if n is in p


A test path p visits edge e if e is in p

Tour , A test path p tours subpath q if q is a subpath of p


Path [ 0, 1, 3, 4, 6
.isits ,od"s 0, 1, 3, 4, 6
.isits "dg"s $0, 1%, $1, 3%, $3, 4%, $4, 6%
/o(rs s()paths $0, 1, 3%, $1, 3, 4%, $3, 4, 6%, $0, 1, 3, 4%, $1, 3, 4, 6%
0 1 3 4 6
May 8, 2014 CSIT5100 ,
Tests an) Test 'aths

path *t+ , The test path e8ecuted by test t

path *T+ , The set of test paths e8ecuted by the set


of tests T

4ach test e8ecutes one and only one test path

A location in a graph *node or edge+ can be reached


from another location if there is a se-uence of
edges from the first location to the second

Syntactic reach , A subpath e8ists in the graph

Semantic reach , A test e8ists that can e8ecute that subpath


May 8, 2014 CSIT5100 10
10
Tests an) Test 'aths
t"st 1
t"st 2
t"st 3
+a,0*to*o,"
t"st 1
t"st 2
t"st 3
+a,0*to*+a,0
/"st Path 1
/"st Path 2
/"st Path 3
No,*d"t"r+i,isti# soft1ar" 2 a t"st #a, "3"#(t" diff"r",t t"st paths
/"st
Path
'"t"r+i,isti# soft1ar" 2 a t"st al1a0s "3"#(t"s th" sa+" t"st path
May 8, 2014 CSIT5100 11
Testing an) Covering Graphs

<e use graphs in testing as follows ,

#e'eloping a model of the software as a graph

7e-uiring tests to 'isit or tour specific sets of nodes)


edges or subpaths

Structural Co'erage Criteria , #efined on a graph


=ust in terms of nodes and edges

#ata $low Co'erage Criteria , 7e-uires a graph to


be annotated with references to 'ariables
May 8, 2014 CSIT5100 12
-o)e an) ")ge Coverage

The first *and simplest+ two criteria re-uire that each


node and edge in a graph be e8ecuted

This statement is a bit cumbersome) so we


abbre'iate it in terms of the set of test re-uirements
Nod" 4ov"rag" $N4% Nod" 4ov"rag" $N4% 5 /"st s"t 5 /"st s"t T T satisfi"s ,od" #ov"rag" o, satisfi"s ,od" #ov"rag" o,
graph graph G G iff for "v"r0 s0,ta#ti#all0 r"a#ha)l" ,od" iff for "v"r0 s0,ta#ti#all0 r"a#ha)l" ,od" n n i, i, N N, ,
th"r" is so+" path th"r" is so+" path p p i, i, path(T) path(T) s(#h that s(#h that p p visits visits n n6 6
Nod" 4ov"rag" $N4% Nod" 4ov"rag" $N4% 5 /! #o,tai,s "a#h r"a#ha)l" ,od" i, &6 5 /! #o,tai,s "a#h r"a#ha)l" ,od" i, &6
May 8, 2014 CSIT5100 13
-o)e an) ")ge Coverage
4dge co'erage is slightly stronger than node co'erage
The &length up to 0( allows for graphs with one node and no edges
:C and 4C are only different when there is an edge and another subpath between a pair of nodes *as in an &if9else( statement+
7dg" 4ov"rag" $74% 7dg" 4ov"rag" $74% 5 /! #o,tai,s "a#h r"a#ha)l" path of 5 /! #o,tai,s "a#h r"a#ha)l" path of
l",gth (p to 1, i,#l(siv", i, &6 l",gth (p to 1, i,#l(siv", i, &6
Nod" 4ov"rag" 5 /! = { 0, 1, 2 }
/"st Path = [ 0, 1, 2
7dg" 4ov"rag" 5 /! = { $0,1%, $0, 2%, $1, 2% }
/"st Paths = [ 0, 1, 2 , [ 0, 2
1
2
0
May 8, 2014 CSIT5100 14
'aths of .ength 1 an) 0

A graph with only one node will not ha'e any edges

>t may be boring) but formally) 4dge Co'erage needs to re-uire :ode Co'erage on this graph

!therwise) 4dge Co'erage will not subsume :ode Co'erage

So we define &length up to 0( instead of simply &length 0(

<e ha'e the same issue with graphs that only ha'e one edge . for 4dge Pair Co'erage 2
0
1
0
May 8, 2014 CSIT5100 15
15
Covering M+%tip%e ")ges

4dge9pair co'erage re-uires pairs of edges) or subpaths of


length 1

The &length up to 1( is used to include graphs that ha'e less


than 1 edges

The logical e8tension is to re-uire all paths 2

Unfortunately) this is impossible if the graph has a loop) so a


wea? compromise is to ma?e the tester decide which paths,
7dg"*Pair 4ov"rag" $7P4% 7dg"*Pair 4ov"rag" $7P4% 5 /! #o,tai,s "a#h r"a#ha)l" path 5 /! #o,tai,s "a#h r"a#ha)l" path
of l",gth (p to 2, i,#l(siv", i, &6 of l",gth (p to 2, i,#l(siv", i, &6
4o+pl"t" Path 4ov"rag" $4P4% 4o+pl"t" Path 4ov"rag" $4P4% 5 /! #o,tai,s all paths i, &6 5 /! #o,tai,s all paths i, &6
8p"#ifi"d Path 4ov"rag" $8P4% 8p"#ifi"d Path 4ov"rag" $8P4% 5 /! #o,tai,s a s"t 8 of t"st 5 /! #o,tai,s a s"t 8 of t"st
paths, 1h"r" 8 is s(ppli"d as a para+"t"r6 paths, 1h"r" 8 is s(ppli"d as a para+"t"r6
May 8, 2014 CSIT5100 1&
Str+/t+ra% Coverage "#a$p%e
Nod" 4ov"rag"
/! = { 0, 1, 2, 3, 4, 5, 6 }
/"st Paths5 [ 0, 1, 2, 3, 6 [ 0, 1, 2, 4, 5, 4, 6
6
0
2
1
3 4
7dg" 4ov"rag"
/! = { $0,1%, $0,2%, $1,2%, $2,3%, $2,4%, $3,6%, $4,5%, $4,6%,
$5,4% }
/"st Paths5 [ 0, 1, 2, 3, 6 [ 0, 2, 4, 5, 4, 6
7dg"*Pair 4ov"rag"
/! = { [0,1,2, [0,2,3, [0,2,4, [1,2,3, [1,2,4, [2,3,6,
[2,4,5, [2,4,6, [4,5,4, [5,4,5, [5,4,6 }
/"st Paths5 [ 0, 1, 2, 3, 6 [ 0, 1, 2, 4, 6 [ 0, 2, 3, 6
[ 0, 2, 4, 5, 4, 5, 4, 6
4o+pl"t" Path 4ov"rag"
/"st Paths5 [ 0, 1, 2, 3, 6 [ 0, 1, 2, 4, 6 [ 0, 1, 2, 4, 5, 4, 6
[ 0, 1, 2, 4, 5, 4, 5, 4, 6 [ 0, 1, 2, 4, 5, 4, 5, 4, 5, 4, 6 9
5
May 8, 2014 CSIT5100 1(
.oops in Graphs

>f a graph contains a loop) it has an infinite number


of paths

Thus) CPC is not feasible

SPC is not satisfactory because the results are


sub=ecti'e and 'ary with testers

Attempts to &deal with( loops,

0@A6s , 48ecute cycles once */B) C) B3 in pre'ious e8ample)


informal+

0@D6s , 48ecute each loop) e8actly once *formaliEed+

0@@6s , 48ecute loops 6 times) once) more than once


*informal description+

1666s , Prime paths


May 8, 2014 CSIT5100 18
18
Si$p%e 'aths an) 'ri$e 'aths

Simple Path , A path from node n


i
to n
j
is simple if no node
appears more than once, except possibly the first and last
nodes are the same

:o internal loops

%ay include other subpaths

A loop is a simple path

Prime Path , A simple path that does not appear as a proper


subpath of any other simple path
8i+pl" Paths 5 [ 0, 1, 3, 0 , [ 0, 2, 3, 0, [ 1, 3, 0, 1 ,
[ 2, 3, 0, 2 , [ 3, 0, 1, 3 , [ 3, 0, 2, 3 , [ 1, 3, 0, 2 ,
[ 2, 3, 0, 1 , [ 0, 1, 3 , [ 0, 2, 3 , [ 1, 3, 0 , [ 2, 3, 0 ,
[ 3, 0, 1 , [3, 0, 2 , [ 0, 1, [ 0, 2 , [ 1, 3 , [ 2, 3 , [ 3, 0 ,
[0, [1, [2, [3
Pri+" Paths 5 [ 0, 1, 3, 0 , [ 0, 2, 3, 0, [ 1, 3, 0, 1 ,
[ 2, 3, 0, 2 , [ 3, 0, 1, 3 , [ 3, 0, 2, 3 , [ 1, 3, 0, 2 ,
[ 2, 3, 0, 1
1 2
0
3
:,0 paths #a, )" #r"at"d )0
#o+posi,g si+pl" paths;
May 8, 2014 CSIT5100 1,
More 'ri$e 'ath "#a$p%e

The following graph has FD simple paths

!nly nine prime paths


Pri+" Paths
[ 0, 1, 2, 3, 6
[ 0, 1, 2, 4, 5
[ 0, 1, 2, 4, 6
[ 0, 2, 3, 6
[ 0, 2, 4, 5
[ 0, 2, 4, 6
[ 5, 4, 6
[ 4, 5, 4
[ 5, 4, 5
73"#(t"
loop o,#"
73"#(t" loop
+or" tha, o,#"
5
0
2
1
3 4
6
73"#(t"
loop 0 ti+"s
May 8, 2014 CSIT5100 20
0in)ing 'ri$e 'aths
5
0
2
1
3 4
6
<", 0
[0
[1
[2
[3
[4
[5
[6 ;
=;> +"a,s path
t"r+i,at"s
<", 1
[0, 1
[0, 2
[1, 2
[2, 3
[2, 4
[3, 6 ;
[4, 6 ;
[4, 5
[5, 4
<", 2
[0, 1, 2
[0, 2, 3
[0, 2, 4
[1, 2, 3
[1, 2, 4
[2, 3, 6 ;
[2, 4, 6 ;
[2, 4, 5 ;
[4, 5, 4 ?
[5, 4, 6 ;
[5, 4, 5 ?
=?> +"a,s
path #0#l"s
<", 3
[0, 1, 2, 3
[0, 1, 2, 4
[0, 2, 3, 6 ;
[0, 2, 4, 6 ;
[0, 2, 4, 5 ;
[1, 2, 3, 6 ;
[1, 2, 4, 5 ;
[1, 2, 4, 6 ;
<", 4
[0, 1, 2, 3, 6 ;
[0, 1, 2, 4, 6 ;
[0, 1, 2, 4, 5 ;
Prime Paths
8i+pl"
paths
May 8, 2014 CSIT5100 21
'ri$e 'ath Coverage

A simple) elegant and finite criterion that re-uires loops


to be e8ecuted as well as s?ipped
Pri+" Path 4ov"rag" $PP4% Pri+" Path 4ov"rag" $PP4% 5 /! #o,tai,s "a#h pri+" path i, &6 5 /! #o,tai,s "a#h pri+" path i, &6

@ill to(r all paths of l",gth 0, 1, 9

/hat is, it s()s(+"s ,od", "dg", a,d "dg"*pair #ov"rag"


May 8, 2014 CSIT5100 22
Test Set Constr+/tion for 'ri$e 'ath
Coverage
5
0
2
1
3 4
6
<", 2
[0, 1, 2
[0, 2, 3
[0, 2, 4
[1, 2, 3
[1, 2, 4
[2, 3, 6 ;
[2, 4, 6 ;
[2, 4, 5 ;
[4, 5, 4 ?
[5, 4, 6 ;
[5, 4, 5 ?
<", 3
[0, 1, 2, 3
[0, 1, 2, 4
[0, 2, 3, 6 ;
[0, 2, 4, 6 ;
[0, 2, 4, 5 ;
[1, 2, 3, 6 ;
[1, 2, 4, 5 ;
[1, 2, 4, 6 ;
<", 4
[0, 1, 2, 3, 6 ;
[0, 1, 2, 4, 6 ;
[0, 1, 2, 4, 5 ;
Prime Paths
/ = {[0,1,2,3,6, [0,1,2,4,6,
[0,1,2,4,5,4,6, [0,2,3,6,
[0,2,4,6, [0,2,4,5,4,6,
[0,2,4,5,4,5,4,6}
Not" that t"st s"t
is ,ot ,"#"ssaril0
(,iA("6
May 8, 2014 CSIT5100 23
Infeasi1%e Test 2e3+ire$ents

An infeasible test re-uirement cannot be satisfied

Unreachable statement *dead code+

A subpath that can only be e8ecuted if a contradiction occurs *G H 6 and G I


6+

%ost test criteria ha'e some infeasible test


re-uirements

>t is usually undecidable whether all test


re-uirements are feasible
May 8, 2014 CSIT5100 24
ata 0%ow Criteria

#efinition *def+ , A location where a 'alue for a 'ariable is stored


into memory) e.g.) 8 J B1K

Use , A location where a 'ariableLs 'alue is accessed) e.g.) E J 8K

def *n+ or def *e+ , The set of 'ariables that are defined by node n
or edge e

use *n+ or use *e+ , The set of 'ariables that are used by node n
or edge e
&oal5 /r0 to ",s(r" that val("s ar" #o+p(t"d a,d (s"d #orr"#tl0
0
2
1
6 3
5
4
B = 42
C = B*8
C = B?2
'"fs5 d"f $0% = {B}
d"f $4% = {C}
d"f $5% = {C}
Ds"s5 (s" $4% = {B}
(s" $5% = {B}
May 8, 2014 CSIT5100 25
4 'airs an) 4 'aths

#U pair , A pair of locations *l


i
) l
j
+ such that a 'ariable v
is defined at l
i
and used at l
j

*6) B+) *6) C+) *1) B+) *1) C+ are #U pairs of G


0
2
1
6 3
5
4
B = 42
C = B*8
C = B?2
B = 0
May 8, 2014 CSIT5100 2&
4 'airs an) 4 'aths

#ef9clear , A path from l


i
to l
j
is def-clear with respect
to 'ariable v if v is not gi'en another 'alue on any of
the nodes or edges in the path

48amples, /6) 0) F) B3) /1) F) C3

Counter9e8amples, /6) 1) F) B3) /6) 1) F) C3


0
2
1
6 3
5
4
B = 42
C = B*8
C = B?2
B = 0
May 8, 2014 CSIT5100 2(
4 'airs an) 4 'aths

7each , >f there is a def9clear path from l


i
to l
j
with
respect to v) the def of v at l
i
reaches the use at l
j

48amples, 7each*6+ J MB) CNK 7each*1+ J MB) CN


0
2
1
6 3
5
4
B = 42
C = B*8
C = B?2
B = 0
May 8, 2014 CSIT5100 28
4 'airs an) 4 'aths

du9path , A simple path that is def9clear with respect


to v from a def of v to a use of v

du *n
i
) n
j
) v+ . the set of du9paths from n
i
to n
j

du*6) B) G+ J /6) 0) F) B3K du*6) C) G+ J /6) 0) F) C3

du *n
i
) v+ . the set of du9paths that start at n
i

du*6) G+ J M/6) 0) F) B3) /6) 0) F) C3N


0
2
1
6 3
5
4
B = 42
C = B*8
C = B?2
B = 0
May 8, 2014 CSIT5100 2,
To+ring 4-'aths

A test path p du-tours subpath d with respect to v if


p tours d and the subpath ta?en is def9clear with
respect to v

Three criteria

Use e'ery def

"et to e'ery use

$ollow all du9paths


May 8, 2014 CSIT5100 30
ata 0%ow Test Criteria
:ll*d"fs #ov"rag" $:'4% :ll*d"fs #ov"rag" $:'4% 5 -or "a#h s"t of d(*paths 5 -or "a#h s"t of d(*paths S S = = du du $ $n n, ,
v v%, /! #o,tai,s at l"ast o," path %, /! #o,tai,s at l"ast o," path d d i, i, S S6 6
:ll*(s"s #ov"rag" $:D4% :ll*(s"s #ov"rag" $:D4% 5 -or "a#h s"t of d(*paths to (s"s 5 -or "a#h s"t of d(*paths to (s"s S S = =
du du $ $n n
i i
, n , n
j j
, , v v%, /! #o,tai,s at l"ast o," path %, /! #o,tai,s at l"ast o," path d d i, i, S S6 6
:ll*d(*paths #ov"rag" $:'DP4% :ll*d(*paths #ov"rag" $:'DP4% 5 -or "a#h s"t 5 -or "a#h s"t S S = = du du $ $ni, nj ni, nj, ,
v v%, /! #o,tai,s "v"r0 path %, /! #o,tai,s "v"r0 path d d i, i, S S6 6

/h", 1" +aE" s(r" that "v"r0 d"f r"a#h"s all possi)l" (s"s

-i,all0, 1" #ov"r all th" paths )"t1"", d"fs a,d (s"s

-irst, 1" +aE" s(r" "v"r0 d"f r"a#h"s a (s"


May 8, 2014 CSIT5100 31
ata 0%ow Testing "#a$p%e
:ll*d"fs for X
[ 0, 1, 3, 4
:ll*(s"s for X
[ 0, 1, 3, 4
[ 0, 1, 3, 5
0
2
1
6 3
5
4
B = 42
C = B*8
C = B?2
'D pairs5
$B,0,4%
$B,0,5%
7v"r0 d"f r"a#h"s a (s"
7v"r0 d"f r"a#h"s all
possi)l" (s"s
:ll possi)l" paths
)"t1"", d"fs a,d th"ir
possi)l" (s"s
:ll*d(*paths for X
[ 0, 1, 3, 4
[ 0, 2, 3, 4
[ 0, 1, 3, 5
[ 0, 2, 3, 5
May 8, 2014 CSIT5100 32
ata 0%ow Testing "#er/ise
:ll*d"fs for X


0
2
1
6 3
5
4
B = 0 C = B*8
C = B?2
May 8, 2014 CSIT5100 33
ata 0%ow Testing "#er/ise
:ll*d"fs for X
[ 2, 3, 4
or
[2, 3, 5
or
[2, 3, 4, 5
:ll*(s"s for X
0
2
1
6 3
5
4
B = 0 C = B*8
C = B?2
May 8, 2014 CSIT5100 34
ata 0%ow Testing "#er/ise
:ll*(s"s for X
[ 2, 3, 4
[ 2, 3, 5
or
[2, 3, 4, 5
:ll*d(*paths for X
0
2
1
6 3
5
4
B = 0 C = B*8
C = B?2
:ll*d"fs for X
[ 2, 3, 4
or
[2, 3, 5
or
[2, 3, 4, 5
May 8, 2014 CSIT5100 35
ata 0%ow Testing "#er/ise
:ll*d(*paths for X
[ 2, 3, 4
[ 2, 3, 5
[2, 3, 4, 5
0
2
1
6 3
5
4
B = 0 C = B*8
C = B?2
:ll*(s"s for X
[ 2, 3, 4
[ 2, 3, 5
or
[2, 3, 4, 5
:ll*d"fs for X
[ 2, 3, 4
or
[2, 3, 5
or
[2, 3, 4, 5
May 8, 2014 CSIT5100 3&
Graph Coverage Criteria
S+1s+$ption
Nod"
4ov"rag"
N4
7dg"
4ov"rag"
74
7dg"*Pair
4ov"rag"
7P4
Pri+" Path
4ov"rag"
PP4
4o+pl"t" Path
4ov"rag"
4P4
:ll*'D*Paths
4ov"rag"
:'DP
:ll*(s"s
4ov"rag"
:D4
:ll*d"fs
4ov"rag"
:'4
CSIT5100
Software Testing -
Graph Coverage for
Source Code
S.C. Cheung
HKUST
Slides adapted from www.introsoftwaretesting.com by Paul Ammann & eff
!ffutt
May 8, 01! CSIT5100
"verview

The most usual application of graph criteria is to


program source

"raph # Usually the control flow graph $C%"&

'ode co(erage # e)ecute e(ery statement

*dge co(erage # e)ecute e(ery branch

+oops # looping structures such as for loops, while


loops, etc.

-ata flow co(erage # augment the C%"

defs are statements that assign (alues to (ariables

uses are statements that use (ariables


May 8, 01! CSIT5100 #
Contro$ %$ow Graphs

A C%" models all e)ecutions of a method by describing


control structures

'odes # statements or se.uences of statements $basic


bloc/s&

*dges # transfers of control

0asic 0loc/ # A se.uence of statements such that if the first


statement is e)ecuted, all statements will be $no branches&

C%"s are sometimes annotated with e)tra information

branch predicates

defs

uses
May 8, 01! CSIT5100 !
C%G & The if State'ent
if (x < y)
{
y = 0;
x = x + 1;
}
else
{
x = y;
}
4
1
2 3
x >= y x < y
x = y
y = 0
x = x + 1
if (x < y)
{
y = 0;
x = x + 1;
}
3
1
2
x >= y
x < y
y = 0
x = x + 1
4
1
2 3
x >= y x < y
x = y
y = 0
x = x + 1
May 8, 01! CSIT5100 5
C%G & The if-(eturn State'ent
if (x < y)
{
return;
}
print (x);
return;
3
1
2
x >= y
x < y
return
print (x)
return
NO edge from node 2 to 3.
The return node mut !e ditin"t.
May 8, 01! CSIT5100 )
*oops

+oops re.uire 1e)tra2 nodes to be added

'odes that do not represent statements or


basic bloc/s
May 8, 01! CSIT5100 +
7
C%G & whi$e and for *oops
x = 0;
while (x < y)
{
y = f (x, y);
x = x + 1;
}
1
x = 0
4 3
y =f(x#y)
x = x + 1
x >= y x < y
for (x = 0; x < y; x++)
{
y = f (x, y);
}
1
x = x + 1
2
3 $
x >= y x < y
y = f (x# y)
4
2
dummy node
x = 0
imp%i"it%y
initi&%i'e %oop
imp%i"it%y
in"rement %oop
May 8, 01! CSIT5100 8
C%G & The case ,switch-
Structure
read ( c) ;
switch ( c )
{
case N:
y = 25;
break;
case Y:
y = 50;
break;
default:
y = 0;
break;
}
print (y);
$
1
re&d ( " )(
" == )N*
y = 0(
!re&+(
2 4 3
" == ),*
def&u%t
y = $0(
!re&+(
y = 2$(
!re&+(
print (y)(
May 8, 01! CSIT5100 .
/0a'p$e Contro$ %$ow 1 Stats
public static void computeStats (int [ ] numbers)
{
int length = numbers.length;
double med, var, sd, mean, sum, varsum;
sum = 0;
for (int i = 0; i < length; i++)
{
sum += numbers [ i ];
}
med = numbers [ length / 2 ];
mean = sum / (double) length;
varsum = 0;
for (int i = 0; i < length; i++)
{
varsum = varsum + ((numbers [ I ] - mean) * (numbers [ I ] - mean));
}
var = varsum / ( length - 1.0 );
sd = Math.sqrt ( var );
System.out.println ("length: " + length);
System.out.println ("mean: " + mean);
System.out.println ("median: " + med);
System.out.println ("variance: " + var);
System.out.println ("standard deviation: " + sd);
}
May 8, 01! CSIT5100 10
public static void computeStats (int [ ] numbers)
{
int length = numbers.length;
double med, var, sd, mean, sum, varsum;
sum = 0;
for (int i = 0; i < length; i++)
{
sum += numbers [ i ];
}
med = numbers [ length / 2 ];
mean = sum / (double) length;
varsum = 0;
for (int i = 0; i < length; i++)
{
varsum = varsum + ((numbers [ I ] - mean) * (numbers [ I ] - mean));
}
var = varsum / ( length - 1.0 );
sd = Math.sqrt ( var );
System.out.println ("length: " + length);
System.out.println ("mean: " + mean);
System.out.println ("median: " + med);
System.out.println ("variance: " + var);
System.out.println ("standard deviation: " + sd);
}
i = 0
i >=
%ength
i < %ength
i++
i >= %ength
i < %ength
i = 0
i++
1
2
3
$
4
-
.
/
May 8, 01! CSIT5100 11
Contro$ %$ow T(s and Test 2aths
1 /C1
2
3
$
4
-
.
/
T0
1. 2 1# 2 3
4. 2 2# 3 3
5. 2 3# 4 3
6. 2 3# $ 3
7. 2 4# 3 3
8. 2 $# - 3
9. 2 -# / 3
:. 2 -# . 3
;. 2 /# - 3
Tet <&th
2 1# 2# 3# 4# 3# $# -# /# -# . 3
7dge 5o=er&ge
May 8, 01! CSIT5100 1
i 1# 4# 6# 7# 8# 9# ; >
Contro$ %$ow T(s and Test 2aths
1 /2C
1
2
3
$
4
-
.
/
T0
1. 2 1# 2# 3 3
4. 2 2# 3# 4 3
5. 2 2# 3# $ 3
6. 2 3# 4# 3 3
7. 2 3# $# - 3
8. 2 4# 3# $ 3
9. 2 $# -# / 3
:. 2 $# -# . 3
;. 2 -# /# - 3
>. 2 /# -# . 3
?. 2 4# 3# 4 3
@. 2 /# -# / 3
Tet <&th
i. 2 1# 2# 3# 4# 3# $# -# /# -# . 3
ii. 2 1# 2# 3# $# -# . 3
iii. 2 1# 2# 3# 4# 3# 4# 3# $# -# /#
-# /# -# . 3
7dgeA<&ir 5o=er&ge
T< T0 toured
ii 1# 5# 7# :
iii 1# 4# 6# 7# 8# 9# ;#
># ?# @
May 8, 01! CSIT5100 1#
Contro$ %$ow T(s and Test 2aths
1 22C
1
2
3
$
4
-
.
/
T0
1. 2 3# 4# 3 3
4. 2 4# 3# 4 3
5. 2 /# -# / 3
6. 2 /# -# . 3
7. 2 -# /# - 3
8. 2 1# 2# 3# 4 3
9. 2 4# 3# $# -# / 3
:. 2 4# 3# $# -# . 3
;. 2 1# 2# 3# $# -# / 3
>. 2 1# 2# 3# $# -# . 3
Tet <&th
i. 2 1# 2# 3# 4# 3# $# -# /# -# . 3
ii. 2 1# 2# 3# 4# 3# 4# 3#
$# -# /# -# /# -# . 3
iii. 2 1# 2# 3# 4# 3# $# -# . 3
i=. 2 1# 2# 3# $# -# /# -# . 3
=. 2 1# 2# 3# $# -# . 3
<rime <&th 5o=er&ge
i 1# 6# 7# 8# 9
T< T0 toured
ii 1# 4# 5# 6# 7# 8# 9#
iii 1# 8# :
i= 6# 7# 8# ;
= >
tBo
one
one
'ero
May 8, 01! CSIT5100 1!
3ata %$ow Coverage for
Source

def # a location where a (alue is stored into memory

) appears on the left side of an assignment $x = 443&

) is an actual parameter in a call and the method changes its (alue

) is a formal parameter of a method $implicit def when method starts&

) is an input to a program

use # a location where (ariable4s (alue is accessed

) appears on the right side of an assignment

) appears in a conditional test

) is an actual parameter to a method

) is an output of the program

) is an output of a method in a return statement

5f a def and a use appear on the same node, then it is only a


-U6pair if the def occurs after the use and the node is in a loop
May 8, 01! CSIT5100 15
/0a'p$e 3ata %$ow 1 Stats
public static void computeStats (int [ ] numbers)
{
int length = numbers.length;
double med, var, sd, mean, sum, varsum;
sum = 0;
for (int i = 0; i < length; i++)
{
sum += numbers [ i ];
}
med = numbers [ length / 2 ];
mean = sum / (double) length;
varsum = 0;
for (int i = 0; i < length; i++)
{
varsum = varsum + ((numbers [ i ] - mean) * (numbers [ i ] - mean));
}
var = varsum / ( length - 1.0 );
sd = Math.sqrt ( var );
System.out.println ("length: " + length);
System.out.println ("mean: " + mean);
System.out.println ("median: " + med);
System.out.println ("variance: " + var);
System.out.println ("standard deviation: " + sd);
}
May 8, 01! CSIT5100 1)
.
1
2
4
3
$
-
/
3ata %$ow Graph for Stats
( num!er )
um = 0
%ength = num!er.%ength
i = 0
i >= %ength
i < %ength
um += num!er 2 i 3
i++
med = num!er 2 %ength C 2 3
me&n = um C (dou!%e) %ength(
=&rum = 0
i = 0
i >= %ength
i < %ength
varsum =
i++
var = varsum / ( length - 1.0 )
sd = Math.sqrt ( var )
print (length, mean, med, var, sd)
tmp = sum + numbersi!
sum = tmp
May 8, 01! CSIT5100 1+
.
1
2
4
3
$
-
/
3ata %$ow Graph for Stats
def (1) = D num!er# um# %ength E
def (2) = D i E
def ($) = D med# me&n# =&rum# i E
ue ($) = D num!er# %ength# um E
de" (#) = $ var, sd %
use (#) = $ varsum, length, mean,
med, var, sd %
ue (3# $) = D i# %ength E
ue (3# 4) = D i# %ength E
def (4) = D um# i E
ue (4) = D um# num!er# i E
ue (-# .) = D i# %ength E
ue (-# /) = D i# %ength E
de" (7) = $ varsum, i %
use (7) = $ varsum, numbers, i, mean %
Ma& #, '01( )*+,-100 1#
6ef &nd Fe T&!%e for Gt&t
Node 6ef Fe
1 D num!er# um#
%ength E
2 D i E
3
4 D um# i E D num!er# i# um E
$ D med# me&n#
=&rum# i E
D num!er# %ength# um E
-
/ D =&rum# i E D =&rum# num!er# i#
me&n E
. D =&r# d E D =&rum# %ength# =&r#
me&n# med# =&r# d E
7dge Fe
(1# 2)
(2# 3)
(3# 4) D i# %ength E
(4# 3)
(3# $) D i# %ength E
($# -)
(-# /) D i# %ength E
(/# -)
(-# .) D i# %ength E
Ma& #, '01( )*+,-100 1.
6F <&ir for Gt&t
=&ri&!%e 6F <&ir
num!er (1# 4) (1# $) (1# /)
%ength (1# $) (1# .) (1# (3#4)) (1# (3#$)) (1# (-#/)) (1#
(-#.))
med ($# .)
=&r (.# .)
d (.# .)
me&n ($# /) ($# .)
um (1# 4) (1# $) (4# 4) (4# $)
=&rum ($# /) ($# .) (/# /) (/# .)
i (2# 4) (2# (3#4)) (2# (3#$)) (2# /) (2# (-#/)) (2#
(-#.))
(4# 4) (4# (3#4)) (4# (3#$)) (4# /) (4# (-#/)) (4#
(-#.))
($# /) ($# (-#/)) ($# (-#.))
(/# /) (/# (-#/)) (/# (-#.))
No defA"%e&r p&th H
different "ope for i
No p&th through gr&ph from
node $ &nd / to 4 or 3
def "ome !efore ue# do
not "ount & 6F p&ir
def &fter ue in %oop#
thee &re =&%id 6F p&ir
Ma& #, '01( )*+,-100 '0
'0
6F <&th for Gt&t
=&ri&!%e 6F <&ir 6F <&th
num!er (1# 4)
(1# $)
(1# /)
2 1# 2# 3# 4 3
2 1# 2# 3# $ 3
2 1# 2# 3# $# -# / 3
%ength (1# $)
(1# .)
(1# (3#4))
(1# (3#$))
(1# (-#/))
(1# (-#.))
2 1# 2# 3# $ 3
2 1# 2# 3# $# -# . 3
2 1# 2# 3# 4 3
2 1# 2# 3# $ 3
2 1# 2# 3# $# -# / 3
2 1# 2# 3# $# -# . 3
med ($# .) 2 $# -# . 3
=&r (.# .) No path needed
d (.# .) No path needed
um (1# 4)
(1# $)
(4# 4)
(4# $)
2 1# 2# 3# 4 3
2 1# 2# 3# $ 3
2 4# 3# 4 3
2 4# 3# $ 3
=&ri&!%e 6F <&ir 6F <&th
me&n ($# /)
($# .)
2 $# -# / 3
2 $# -# . 3
=&rum ($# /)
($# .)
(/# /)
(/# .)
2 $# -# / 3
2 $# -# . 3
2 /# -# / 3
2 /# -# . 3
i (2# 4)
(2# (3#4))
(2# (3#$))
(4# 4)
(4# (3#4))
(4# (3#$))
($# /)
($# (-#/))
($# (-#.))
(/# /)
(/# (-#/))
(/# (-#.))
2 2# 3# 4 3
2 2# 3# 4 3
2 2# 3# $ 3
2 4# 3# 4 3
2 4# 3# 4 3
2 4# 3# $ 3
2 $# -# / 3
2 $# -# / 3
2 $# -# . 3
2 /# -# / 3
2 /# -# / 3
2 /# -# . 3
May 8, 01! CSIT5100 1
'1
34 2aths for Stats 1 5o
3up$icates
There are 78 -U paths for Stats, but only 9: uni.ue
2 1# 2# 3# 4 3
2 1# 2# 3# $ 3
2 1# 2# 3# $# -# / 3
2 1# 2# 3# $# -# . 3
2 2# 3# 4 3
2 2# 3# $ 3
2 4# 3# 4 3
2 4# 3# $ 3
2 $# -# / 3
2 $# -# . 3
2 /# -# / 3
2 /# -# . 3
$ expe"t & %oop not to !e IenteredJ
$ reKuire &t %e&t one iter&tion of & %oop
2 reKuire &t %e&t tBo iter&tion of & %oop
May 8, 01! CSIT5100
Test Cases and Test 2aths
Tet 5&e L num!er = (44) ( %ength = 1
Tet <&th L 2 1# 2# 3# 4# 3# $# -# /# -# . 3
1ddition&% 6F <&th "o=ered (no idetrip)
2 1# 2# 3# 4 3 2 2# 3# 4 3 2 4# 3# $ 3 2 $# -# / 3 2 /# -# . 3
The five stars that require at least one iteration of a loop
Tet 5&e L num!er = (2# 10# 1$) ( %ength = 3
Tet <&th L 2 1# 2# 3# 4# 3# 4# 3# 4# 3# $# -# /# -# /# -# /# -# . 3
6F <&th "o=ered (no idetrip)
2 4# 3# 4 3 2 /# -# / 3
The two stars that require at least two iterations of a loop
Other 6F p&th reKuire &rr&y Bith %ength 0 to +ip %oop
4ut the method f&i% Bith di=ide !y 'ero on the t&tement H
me&n = um C (dou!%e) %ength(
1 f&u%t B&
found
May 8, 01! CSIT5100 #
Su''ary

Applying the graph test criteria to control flow graphs is


relati(ely straightforward

;ost of the de(elopmental research wor/ was done with C%"s

A few subtle decisions must be made to translate


control structures into the graph

Some tools will assign each statement to a uni.ue


node

These slides and the boo/ uses basic bloc/s

Co(erage is the same, although the boo//eeping will differ


CSIT5100
Building Testing Tools
Instrumentation for
Graph
S.C. Cheung
HKUST
Slides adapted from www.introsoftwaretesting.com by Paul Ammann & eff
!ffutt
May 8, 01! CSIT5100
Categories of Test Tools

"esearch

Pri#ate non$commercial

Commercial
Advanced techniques
Generators
Very powerful
Often code-based
Usually incomplete
General purpose
Moderate techniques
Acceptors
Mostly complete
Some code-based
Often special purpose
Test manaement
Simple coverae
Metrics
!ode independent
May 8, 01! CSIT5100 "
Types of Test Tools

Co#erage analy%ers
&Acceptors'

(hat co#erage ) &most


common is node'

(hat le#el) &sometimes


ob*ect code'

+low graph generators

,etrics

-nstrumentation support

Test e.ecution automation

"uns scripts and reports


results

Unit/ HttpUnit/ 0

Capture 1 replay

Useful for 2U-s

Stubs and 3ri#ers

Test data generators

2raph path 4 based

3ata flow

5ogic based

+unctional

,utation

"andom

!nly random test data


generators e.ist
Tools Instrumentation
The 6ey technology behind many
test tools is 7instrumentation8
May 8, 01! CSIT5100 5
Tools Instrumentation

Co#erage analysis is measured with instrumentation

-nstrument 9 !ne or more statements inserted into


the program to monitor some aspect of the program

,ust not affect the beha#ior

,ay affect timing

Source le#el or ob*ect code le#el


public int min "int A# $%
&
int m ' A(
if "A ) $%
&
m ' $(
*
return "m%(
*
Mar+, -if body is reached.
May 8, 01! CSIT5100 #
Instrumenting for Statement
Co$erage
:. ;ach node is gi#en a uni<ue id =

>ode = or statement =
?. Create an array inde.ed by id =s 4 nodeCo#er @ A
B. -nsert an instrument at each node

nodeCo#er @ i A CCD
E. Sa#e nodeCo#er @ A after each e.ecution

,ust accumulate results across multiple test cases


May 8, 01! CSIT5100 %
Statement Co$erage &'ample
/
0 1
2
3 4 5
6
7
28
int node!over9: ' &8#8#8#8#8#8#8#8#8#8*
nc 90:;;
nc 91:;;
nc 94:;; nc 95:;;
nc 9/:;;
nc 97:;;
nc 93:;;
nc 928:;;
nc 96:;;
<ead "node!over 9:%
node!over 92: ;;
After runnin a sequence of After runnin a sequence of
tests# any node for which tests# any node for which
node!over9node:''8 has node!over9node:''8 has not not
been covered= been covered=
May 8, 01! CSIT5100 8
&dge Co$erage
Instrumentation
/
0 1
2
3 4 5
6
7
28
int ede!over9: '
&8#8#8#8#8#8#8#8#8#8#8#8#8*
ec 91:;; ec 92:;;
ec 90:;;
<ead "ede!over 9:%
>or each ede e# put >or each ede e# put
ede!over9e:;; on the ede= ede!over9e:;; on the ede=
?f ede!over9e: '' 8# e has ?f ede!over9e: '' 8# e has
not not been covered= been covered=
@ote that the arrays could @ote that the arrays could
be boolean be boolean
May 8, 01! CSIT5100 (
)ll*+ses Co$erage
Instrumentation
/
0 1
2
4 5
def"2% ' &A# y*
use"4% ' &A* use"5%
' &A*
def"1% ' &y*
use"/% ' &y*
use!over 94# A# def!over9A:: ;;
use!over 95# A# def!over9A:: ;;
use!over 9/# y# def!over9y:: ;;
def!over 9A: ' 2
def!over 9y: ' 2
def!over 9y: ' 1
>or each variable# +eep >or each variable# +eep
trac+ of its current trac+ of its current def def
location= location=
At each At each use use# increment a # increment a
counter counter for the def that for the def that
reached it= reached it=
May 8, 01! CSIT5100 10
Instrumentation Summary

-nstrumentation can be added in multiple copies of the program

Source code

a#a byte code &or other intermediate code'

;.ecutable

-nstrumentation must not change or delete functionality

!nly add new functionality

-nstrumentation may affect timing beha#ior

"e<uires the program to be parsed

!nce parsed/ inserting instruments is straightforward

,ost challenging part is the user interface

Present reports as dumps of instrument arrays )

Present tables )

Program source with colored annotations )

2raph of program with colored annotations )


CSIT5100
UML Overview
May 8, 2014
S.C. Cheung
HKUST
Trend Software Demand

hundred billion dollars/year spent worldwide and growing

essential part of almost all organizations

key part of many products ! embedded systems

essential for designing many products


D
e
m
a
n
d
1960 1970 1980 1990 2000 2010
Personal computing,
information,
education
Commercial
Scientific & Technical
Trend Software Compe!ity

sample code sizes"


#
handheld bar code scanner" $%&%K'(C
#
cellular telephone" )%K'(C
#
*T+" ,%%K'(C
M
a
n
"
m
o
n
t
#
$
100 200 300 400 500 600
2000
4000
6000
8000
1000s of language statements
CS-T&$%% . S.C. Cheung
Software Cri$i$
$. schedule and cost estimates often grossly
inaccurate
#
o/er schedule
#
o/er budget
0. 1uality of software is some often less than
ade1uate ! unreliable2 infle3ible2 ...
CS-T&$%% & S.C. Cheung
Importan%e of &e'(irement
Modein)

a $44. sur/ey of )&% companies and o/er


5%% software pro6ects showed"
#
)$7 canceled before completed
#
only $,7 deli/ered on time2 within budget
8small company9
#
only 47 deli/ered on time2 within budget
8large company9
WHY?
Source" The Chaos :eport2 The Standish ;roup2 $44.
CS-T&$%% , S.C. Cheung
Ca($e$

incomplete re1uirements $).$7

lack of user in/ol/ement $0..7

lack of resources $%.,7

unrealistic e3pectations 4.47

lack of e3ecuti/e support 4.)7

changing re1uirements and specifications 5.<7

lack of planning 5.$7

system no longer needed <.&7


Requirements modeling involved in most cases
CS-T&$%% < S.C. Cheung
CS-T&$%% 5 S.C. Cheung
CS-T&$%% 4 S.C. Cheung
CS-T&$%% $% S.C. Cheung
CS-T&$%% $$ S.C. Cheung
CS-T&$%% $0 S.C. Cheung
CS-T&$%% $) S.C. Cheung
CS-T&$%% $. S.C. Cheung
CS-T&$%% $& S.C. Cheung
CS-T&$%% $, S.C. Cheung
CS-T&$%% $< S.C. Cheung
Importan%e of &e'(irement
Modein)
=ormalized cost to fi3 a problem
:e1uirements >$
?esign >&
Coding >$%
Testing >0%
*fter deli/ery >0%%
BUT, requirement modeling is DIFFICULT
CS-T&$%% $5 S.C. Cheung
Diemma

*ccurate re1uirement relies on domain


e3pertise

@UT domain e3perts are rare resources in


financial organizations
! *ow to ma+e t#e re'(irement %apt(rin) e,e%tive
-eed to re%on%ie t#e f(ndamenta
di,eren%e$ .etween pro)rammer$
and ($er$
*rising due to different stakes of interests
CS-T&$%% 0% S.C. Cheung
CS-T&$%% 00 S.C. Cheung
UML/ 0#at i$ it/

To unify /arious e3isting (( design notations

*s a generalpurpose /isual modeling language

=(T intended to be a de/elopment method

=( stepbystep de/elopment process

-ntended to support a wide /ariety of e3isting


software process

*dopted by the (+; 8(b6ect +anagement


;roup9 as the standard notation for
ob6ectoriented design
CS-T&$%% 0) S.C. Cheung
UML 1iew$ and Dia)ram$
Structural ?ynamic
!tatic
vie"
Use case
vie"
-mplementation
/iew
?eployment
/iew
!tate
mac#ine
vie"
*cti/ity
/iew
Interaction
vie"
Class
diagram
Use case
diagram
Component
diagram
?eployment
diagram
(b6ect
diagram
Statechart
diagram
Se1uence
diagram
Collaboration
diagram
*cti/ity
diagram
CS-T&$%% 0. S.C. Cheung
2n 2TM Sy$tem
Real Problem
User
Use Case View
Withdraw one!
"eposit one!
Transfer between
#ccounts
Use case
CS-T&$%% 0& S.C. Cheung
T#e 0it#draw Money U$e Ca$e
The sequence of actions for a path through
this use case is

1. The User identifies himself or herself$
2. The User chooses from which account
to withdraw mone! and specifies how much
to withdraw$
3. The s!stem deducts the amount from the account
and dispenses the mone!$
CS-T&$%% 0, S.C. Cheung
-onf(n%tiona &e'(irement$
The following re%uirement can be attached to the
Withdraw one! use case&

The response time for a User measured from selecting
the amount to withdraw to the deli'er! of the bills
should be less than () seconds in *+, of all cases$
CS-T&$%% 0< S.C. Cheung
2nay$i$ Ca$$e$
Withdraw one!
Withdraw one!
Use-Case odel #nal!sis odel
..trace//
"ispenser
Cashier
0nterface
Withdrawal
#ccount
CS-T&$%% 05 S.C. Cheung
1aidation
User
1& identif! 2& re%uest withdrawal
+$ dispense mone!
3& authori4e dispense
(& 'alidate and withdraw
&#T 5Cashier
0nterface6
&#T
5"ispenser6
&#ccount
&Withdrawal
CS-T&$%% 04 S.C. Cheung
2nay$i$ Mode
Use-Case odel
Withdraw one!
"eposit one!
Transfer between
#ccounts
User
#nal!sis odel
Aithdrawal
Transfer
?eposit
Sa/ings
Current Credit Card
Customer *ccount
B B
owns
?ispenser Cashier -nterface
*T+
B
B
B B
$ B B
B
*uthorization
$
$
Transaction
$ B
performs
B
B
concerns
*T+ Card
B
B
accesses
$
$ refers to
$
B
authorizes
$
B
" User
" Cashier
-nterface
" Aithdrawal " Cash Card " *uthorization " *ccount " ?ispenser
insert card
enter password
check card
check password
get authorization
/alidate password
re1uest password
re1uest transaction
select transaction
select account
enter account
re1uest amount
enter amount
withdraw
get accounts
get authorized accounts
card ok
withdraw
withdraw ok
return accounts
return accounts
dispense cash
transaction ok
take cash C card
cash dispensed
return authorization
password ok
password ok
2TM Sy$tem
Interaction View
" Cashier
-nterface
" Aithdrawal " Cash Card " *uthorization " *ccount " ?ispenser
" User
Se'(en%e Dia)ram 3Cont45
" User
" Cashier
-nterface
" Aithdrawal " Cash Card " *uthorization " *ccount " ?ispenser
insert card
enter password
check card
check password
get authorization
/alidate password
re1uest password
re1uest transaction
select transaction
select account
enter account
re1uest amount
enter amount
withdraw
get accounts
get authorized accounts
card ok
withdraw
withdraw ok
return accounts
return accounts
dispense cash
transaction ok
take cash C card
cash dispensed
return authorization
password ok
password ok
S(.$y$tem$
Ban
!ustomer
"is#la$
%e$ &a'
!ar' (ea'er
"is#enser
)ensor
"is#enser
*ee'er
!as+
!ounter
!lient
,anager
-it+'rawal
.ransaction
,anager
//ser0ice
su1s$stem22
-it+'raw
,anagement
3ccount
&ersistent
!lass
3ccount
,anager
-it+'rawal
"is#ensing
.ransfer
//su1s$stem22
3., Interface
//su1s$stem22
.ransaction
,anagement
//su1s$stem22
3ccount
,anagement
3ut+ori4ation
!as+ !ar'
Layer 2r%#ite%t(re
3##lication5s#ecific la$er
3##lication5general la$er
3., Interface
.ransaction
,anagement
-it+'rawal
,anagement
6-ra##er7
3ccount
,anagement
,i''leware la$er
8a0a.a##let 8"B!
"B,)63ccount7
)$stem software la$er
Impementation Mode
"is#enser
)ensor
"is#enser
*ee'er
!as+
!ounter
!lient
,anager
//file22
'is#enser.c
//file22
client.c
//e9ecuta1le22
client.e9e
//com#ilation22
"esign ,o'el Im#lementation ,o'el
Depoyment Mode
"*T+
Client
"leased
lines
"*T+
ser/er
"*T+
*pplication
Ser/er
"logging
ser/er
"*T+
Client
"*T+
Client
"*T+
?ata Ser/er
&#T
0nterface
&#T
0nterface
&#T
0nterface
&Transaction
anagement
&#ccount
anagement
Client
Ser'er
7an8
8"B!
:e0el 4
Ban
!ustomer

Aho are the users of the systems2 and what are they
trying to doD

Ahat are the Ereal worldE ob6ects and the


associations among themD

How do ob6ects collaborating within each use case


interactD

How will realtime control issues be handledD

How to build a system on a nutsandbolts le/elD


6(ndamenta 7(e$tion$ for 8very
Software Deveopment
;se !ases
3nal$sis !lass "iagrams
Interaction "iagrams
)tate "iagrams
"esign !lass "iagrams
Inception Elaboration Construction Transition
Software Deveopment 9ro%e$$
Phases
Core Workflows
Requirements
Analysis
Design
Implementation
Testing
iter$
%&
iter$
%'
( ( ( ( (
iter$
%n)&
iter$
%n
Iterations
ma<or milestone
CS-T&$%% )5 S.C. Cheung
&eferen%e$

The Unified +odeling 'anguage :eference +anual2 F. :umbaugh2 -. Facobson2 ;.


@ooch2 *ddisonAesley2 $444

The Unified +odeling 'anguage User ;uide2 ;. @ooch2 F. :umbaugh2 -.


Facobson2 *ddisonAesley2 $444

The Unified Software ?e/elopment Grocess2 -. Facobson2 ;. @ooch2 F.


:umbaugh2 *ddison Aesley2 $444

Hisual +odeling with :ational :ose and U+'2 T. Iuatrani2 *ddison Aesley2 $445

*pplying Use Cases * Gractical ;uide2 ;. Schneider2 F.G. Ainters2 *ddison


Aesley2 $445

(b6ect(riented Systems ?e/elopment using the Unified +odeling 'anguage2 *li


@ahrami2 +c;raw Hill2 $444
S.C. Cheung
HKUST
CSIT5100

May 8, 2014
CSIT5100 2 scc
UML? What is it?

To unify various existing OO design notations

s a genera!"#ur#ose visua! $ode!ing !anguage

%OT intended to &e a deve!o#$ent $ethod

%O ste#"&y"ste# deve!o#$ent #rocess

Intended to su##ort a 'ide variety of existing soft'are


#rocess

do#ted &y the O() *O&+ect (anage$ent )rou#, as


the standard notation for o&+ect"oriented design
CSIT5100 - scc
UML Views and Diagras
Structura! .yna$ic
Static
view
Use case
view
I$#!e$entation
vie'
.e#!oy$ent
vie'
State machine
view
Activity
view
Interaction
view
C!ass
diagra$
Use case
diagra$
Co$#onent
diagra$
.e#!oy$ent
diagra$
O&+ect
diagra$
Statechart
diagra$
Se/uence
diagra$
Co!!a&oration
diagra$
ctivity
diagra$
Understanding !"siness #r$%ess
in &%ti'ity Diagras
CSIT5100 5 scc
UML Views and Diagras
Structura! .yna$ic
Static
view
Use case
view
I$#!e$entation
vie'
.e#!oy$ent
vie'
State machine
view
ctivity
vie'
Interaction
view
C!ass
diagra$
Use case
diagra$
Co$#onent
diagra$
.e#!oy$ent
diagra$
O&+ect
diagra$
Statechart
diagra$
Se/uence
diagra$
Co!!a&oration
diagra$
ctivity
diagra$
CSIT5100 0 scc
() * #r$%ess M$rtgage +e,"est
Prepare incoming
documents
Index
documents
Make electronic
file
Complete request
Check data for life
insurance
raw up contract
mortgage!deed
Calculate data for
construction mortgage
raw up
insurance policy
Pay provision to
insurance agent
Mortgage
Application
Insurance
Policy
() * #r$%ess M$rtgage +e,"est
Prepare incoming
documents
Index
documents
Make electronic
file
Complete request
Check data for life
insurance
raw up contract
mortgage!deed
Calculate data for
construction mortgage
raw up
insurance policy
Pay provision to
insurance agent
Customer
department
Insurance
department
Loan
department
s'i$!ane
CSIT5100 1 scc
()a-.e /rder #r$%essing
Use Case
"xample Process Order use case
2hen 'e receive an order3 'e chec4 each !ine ite$ on the
order to see if 'e have the goods in stoc4. If 'e do3 'e
assign the goods to the order. If this assign$ent sends the
/uantity of those goods in stoc4 &e!o' the reorder !eve!3
'e reorder the goods. 2hi!e 'e are doing this3 'e chec4
to see if the #ay$ent is O.K. If the #ay$ent is O.K. and
'e have the goods in stoc43 'e dis#atch the order. If the
#ay$ent is O.K.3 &ut 'e do not have the goods3 'e !eave
the order 'aiting. If the #ay$ent is not O.K.3 'e cance!
the order.
CSIT5100 10 scc
()a-.e /rder #r$%essing
&%ti'ity Diagra
Receive
Order
Reorder
Item
Dispatch
Order
Check
Line
Item
Assign to
Order
Authorize
Payment
Cancel
Order
for each line
item on order
*
[in stock]
[need to
reorder]
[stock assigned to
all line items and
payment authorized]
[succeeded]
[failed]
CSIT5100 11 scc
()a-.e +e-.enish S"--.y
Use Case
"xample Replenish Supply use case
2hen a su##!y de!ivery co$es in3 'e !oo4 at the
outstanding orders and decide 'hich one 'e can
fi!! fro$ this inco$ing su##!y. 2e then assign
each of these to its a##ro#riate orders. .oing this
$ay re!ease those orders for dis#atching. 2e #ut
the re$aining goods into stoc4.
CSIT5100 12 scc
()a-.e +e-.enish S"--.y
&%ti'ity Diagra
Receive
Supply
Choose
Outstanding
Order Items
Assign
Goods to
Order
for each chosen
order item
*
[all outstanding
order items filled]
[stock assigned to
all line items and
payment authorized]
Dispatch
Order
Add
Remainder
to Stock
CSIT5100 1- scc
()a-.e /rder
#r$%essing0re-.enish S"--.y
Receive
Order
Reorder
Item
Dispatch
Order
Check
Line
Item
Assign
Order
Authorize
Payment
Cancel
Order
for each line
item on order
*
[in stock]
[need to
reorder]
[stock assigned to
all line items and
payment authorized]
[succeeded]
[failed]
Receive
Supply
Choose
Outstanding
Order Items
Assign
Goods to
Order
for each chosen
order item
*
[all outstanding
order items filled]
Add
Remainder
to Stock
CSIT5100 15 scc
Swi.anes
Receive
Order
Reorder
Item
Dispatch
Order
Check
Line
Item
Assign to
Order
for each line
item on order
*
[in stock]
[need to
reorder]
[stock assigned to
all line items and
payment authorized]
Authorize
Payment
Cancel
Order
[succeeded]
[failed]
Receive
Supply
Choose
Outstanding
Order Items
Assign
Goods to
Order
for each chosen
order item
*
[all outstanding
order items filled]
Add
Remainder
to Stock
Order
Processing
inance
Stock
!anager
CSIT5100 15 scc
C$nne%t$r
Receive
Order
Reorder
Item
Dispatch
Order
Check
Line
Item
Assign to
Order
for each line
item on order
*
[in stock]
[need to
reorder]
[stock assigned to
all line items and
payment authorized]
Authorize
Payment
Cancel
Order
[succeeded]
[failed]
Receive
Supply
Choose
Outstanding
Order Items
Assign
Goods to
Order
for each chosen
order item
*
[all outstanding
order items filled]
Add
Remainder
to Stock
Order
Processing
inance
Stock
!anager

connectors
&d'an%ed 1$tati$n
CSIT5100 16 scc
&%ti'ity*$23e%t 4.$w
+e.ati$nshi-s
Pay
Re"uest
service
#ake
order
Deliver
order
Collect
order
ill
order
Customer Sales Stockroom
ter$ination
CSIT5100 11 scc
&%ti'ity*$23e%t 4.$w
+e.ati$nshi-s
Pay
Re"uest
service
#ake
order
Deliver
order
Collect
order
ill
order
Customer Sales Stockroom
Order
[placed]
Order
[entered]
Order
[filled]
Order
[delivered]
CSIT5100 17 scc
4.$w Terinati$n
a&ort action
CSIT5100 20 scc
Tie ('ent
CSIT5100 21 scc
()%e-ti$n 5and.ing
exce#tion
hand!ers
CSIT5100 22 scc
Interr"-ts
CSIT5100 2- scc
When T$ Use &%ti'ity Diagras
8
in situations 'here a!! or $ost of the events re#resent the
co$#!etion of interna!!y"generated activities
procedural flow of control
8
to $ode! #ara!!e! &ehavior
9
'or4f!o's
9
$u!ti"threaded #rogra$s
8
genera!!y used in the ear!y stages of design
each activity must #e expanded as one or more
operations assigned to a specific class
+e,"ireent Ca-t"ring
S.C. Cheung
CSIT5100 25 scc
UML Views and Diagras
Structura! .yna$ic
Static
view
Use case
view
I$#!e$entation
vie'
.e#!oy$ent
vie'
State machine
view
ctivity
vie'
Interaction
view
C!ass
diagra$
Use case
diagra$
Co$#onent
diagra$
.e#!oy$ent
diagra$
O&+ect
diagra$
Statechart
diagra$
Se/uence
diagra$
Co!!a&oration
diagra$
ctivity
diagra$
CSIT5100 20 scc
Use Case M$de.

.escri&es syste$ &ehavior fro$ users$ perspectives via


actions and reactions.

.efines syste$ &oundary and re!ations &et'een the syste$


and its environ$ent

Contains actors and use cases


CSIT5100 26 scc
&%t$rs

externa! entities interacting 'ith the syste$

#resent a ro!e3 e.g.3 :uyer or Se!!er

actor cou!d &e su&c!assed

actor description; needs < res#onsi&i!ities


Buyer
etailer
Individual Customer
CSIT5100 21 scc
" so$ething outside the syste$ that interacts 'ith it
" #rovides in#ut to or ta4es out#ut fro$ the syste$
" a ro!e a user can #!ay $u!ti#!e ro!es #ossi&!e
primary actor " interacts direct!y 'ith the syste$
secondary actor " interacts indirect!y 'ith the syste$
&rief!y descri&e the ro!e each actor #!ays 'hen interacting 'ith
the syste$
4inding the &%t$rs
actor name
CSIT5100 27 scc
&%t$r Des%ri-ti$n $6 an In'$i%e
Syste
Buyer
! Buyer represents a person "ho is responsi#le for #uying goods or services$
%his person may #e an individual &i$e$' not affiliated "ith a company( or
someone "ithin a #usiness organization$ %he Buyer of goods and services
needs the system to send orders and to pay invoices$
Seller
! )eller represents a person "ho sells and delivers goods or services$ %he
)eller uses the system to look for ne" orders and to send order
confirmations' invoices' and payment reminders$
Accounting System
%he !ccounting )ystem is responsi#le for keeping account #alances$
%he !ccounting )ystem needs the system to send it verified transactions$
Use Case Diagra
Buyer
)eller
*lace Order
List Order
Confirm Order
initiator
initiator initiator
*ayment eminder
!ccounting
)ystem *ay Invoice
*erform %ransaction
+alidate
,,e-tends..
initiator
,,includes..
)ystem
#oundary
initiator
Invoice Buyer
initiator
CSIT5100 -1 scc
Use Case M$de. 7 Use Case
a s#ecific 'ay of using the syste$ &y #erfor$ing
so$e #art of the functiona!ity
constitutes a co$#!ete course of events initiated &y
an actor

t initia! stage3 'e focus on the nor$a! or usua! course of


events
postpone exceptions% alternate ways of doing things
provide a description of the purpose of the use case
and a high!level definition of its functionality
use/case name
CSIT5100 -2 scc
Use Case Des%ri-ti$n

=ur#ose

ctors

=re"conditions

>!o' of ?vents
9 interactions &et'een actors and the syste$
9 &usiness !ogic

%ot a!!o'ed #aths *if any,

!ternative #aths *if any,

?xce#tions *if any,

Usage of o&+ects3 va!ues3 and resources

=ost"conditions
CSIT5100 -- scc
#ay In'$i%e Use Case
Purpose: !llo" #uyers to pay outstanding invoice&s(
Actors: Buyer' !ccounting )ystem
Preconditions: %he #uyer has received the goods or services ordered and
at least one invoice from the system$ %he #uyer no" plans to schedule the
invoice&s( for payment$
Flow of Events
0$ %he #uyer invokes the use case #y #eginning to #ro"se the invoices
received #y the system$ %he system checks that the content of each
invoice is consistent "ith the order confirmations received earlier$
1$ %he #uyer decides to schedule an invoice for payment #y the #ank' and
the system generates a payment re2uest to transfer money to the seller3s
account$ ! #uyer may not schedule the same invoice for payment t"ice$
4$ Later' if there is enough money in the #uyer3s account' a payment
transaction from the #uyer3s account to the seller3s account$ %he #uyer
and seller are notified of the result of the transaction$ %he #ank collected
a fee for the transaction' "hich is "ithdra"n from the #uyer3s account$
5$ %he use case instance terminates$
CSIT5100 -5 scc
#ay In'$i%e Use Case 8C$nt9d:
CSIT5100 -5 scc
Che%;.ist
In so$e situations3 infor$a! re/uire$ents of a syste$ are
avai!a&!e textua!!y3 e.g.3 re"engineering of an existing syste$
9
Have a!! the re/uire$ents &een a!!ocated to a use
case@
9
Has the sa$e re/uire$ent &een a!!ocated to
$u!ti#!e use cases@
9
re there use cases not referenced &y infor$a!
re/uire$ents
CSIT5100 -0 scc
4"rther &%ti'ities

Structuring use cases


9
)enera!iAation *co$$on or shared functiona!ity,
9
?xtend re!ationshi# *additiona! functiona!ity,
9
Inc!ude re!ationshi#

na!ysis and ?!a&oration of Use Case

=rototy#e user interface


9
create a !ogica! user"interface design
9
create a #hysica! user"interface design and
#rototy#e
CSIT5100 -6 scc
Str"%t"ring Use Cases

Inc!udes Binc!udesC
9
ex#!icit!y incor#orates the &ehavior of another
use case
9
exa$#!es;

Dplace orderE inc!udes Dvalidate userE

Dcancel orderE inc!udes Dfind orderE

Danalyze riskE inc!udes DvaluationE


place order validate user
6includes7
CSIT5100 -1 scc
Str"%t"ring Use Cases

?xtend
9
extends a $ore genera! use case &y adding
s#ecific actions
9
extension #oint and condition
9
?xa$#!es;

Dcheck passwordE extends Dvalidate userE

Dfingerprint scanE extends Dvalidate userE


validate user
check pass"ord
6e-tend7
e-tension points
CSIT5100 -7 scc
The 1e)t Ste-<ana.ysis

na!ysis
9
(ore #recise s#ecification of each use case

rtifacts
9
C!ass diagra$
9 Interaction diagra$s
9 ctivity diagra$s
9
S#ecia! re/uire$ents < exce#tions
9
na!ysis #ac4ages

organiAe design $ode!s into s$a!!er3 $anagea&!e #ieces

identify reusa&!e service #ac4ages


CSIT5100 50 scc
De.i'era2.es $6 +e,"ireent
Ca-t"ring

.o$ain $ode!
9
4ey &usiness o&+ects and their re!ations

Use case $ode!


9
actors < their descri#tions
9 use cases < their descri#tions *i.e.3 event f!o's,
9 use case diagra$ re!ating various use cases
9
!ist of critica! use cases that

affect the syste$ architecture

$ust &e e!a&orated *and #ossi&!y rea!iAed, &efore others

UI .esign and =rototy#e


CSIT5100 51 scc
#r$t$ty-e User Inter6a%e

Creating a !ogica! user"interface design


9
2hich user"interface e!e$ents are needed to
ena&!e the use cases@
9
Ho' shou!d they &e re!ated to each other@
9
2hat shou!d they !oo4 !i4e@
9
Ho' shou!d they &e $ani#u!ated@
CSIT5100 52 scc
L$gi%a. User Inter6a%e

:uyer UI
9
"F chec4 ne' invoices
9
G" inconsistent invoices
9
"F #ay invoice
9
"F fi!! in #ay$ent detai!s
9
G" #ay$ent reference < confir$ation
9
"F /uery #ay$ent status
9
"F s#!it invoice
9
H
Buyer
CSIT5100 5- scc
#hysi%a. UI Design
8ile Check Invoice etrieval *ayment 9elp
Open Invoice
Close Invoice
:-it
;e"<
=elete$$$
)earch$$$
;e"<
Open<
>uery$$$
Contents
?sing 9elp
*rocedures
Commands
=ialog Bo-es
!#out $$$
CSIT5100 55 scc
#hysi%a. UI Design
Invoice ;ame@
8ile !n Invoice
Invoices =irectories
OA
Cancel
9elp
eference Information
CSIT5100 55 scc
#hysi%a. UI Design
Invoice ef@
Invoice etrieval :ngine
OA Cancel
=ate@
Aey"ords@
)eller@
CSIT5100 50 scc
UI #r$t$ty-e

I$#!e$ent the UI using visua! su##ort too!


9
Iisua! :asic
9
Iisua! Caffee
9
J&ui!der
9
2e& =u&!isher
9
H3 etc

)et ear!y feed&ac4 fro$ users


CSIT5100 56 scc
Change $6 Shi6t #attern 81$ra.
C$"rse:
1. The Su#ervisor s#ecifies the attri&utes of the ne' shift
#attern3 such as ne' #attern no3 ne' day no. and effective
date.
2. >or assign$ent &y staff3 #rovide the staff nu$&er.
-. >or assign$ent &y grou#3 #rovide the sectionKcre'. Then
se!ect the staff fro$ the avai!a&!e !ist.
5. The ne'!y assigned shift #attern is chec4ed against shift
#o!icies. If any vio!ation3 Su#ervisor is #ro$#ted to correct the
entry or choose to a&ort.
CSIT5100 51 scc
()a-.es * Change Shi6t
#attern
CSIT5100 57 scc
Uni=ed S$6tware De'e.$-ent
#r$%ess

Incre$enta! and iterative

Use case driven

rchitectura! centric
CSIT5100 50 scc
Iterati'e and In%reenta.
Incremental
Iterative
A #ypical Process
CSIT5100 51 scc
#"re Water6a.. De'e.$-ent
#r$%ess
&equirements
Analysis
esign
Coding
'esting
L
I
S
K
TI(?
=ro&!e$; .e!ays Lis4 Leduction
CSIT5100 52 scc
Iterati'e De'e.$-ent
&%%e.erates +is; +ed"%ti$n
L
I
S
K
Iterative
2aterfa!!
TI(?
CSIT5100 5- scc
Inception Elaboration Construction Transition
Uni=ed De'e.$-ent #r$%ess
* Li6e Cy%.e
Phases
Core $ork%lo&s
Requirements
Analysis
Design
Coding
Testing
iter(
)*
iter(
)+
, , , , ,
iter(
)n!*
iter(
)n
Iterations
maBor milestone
CSIT5100 55 scc
Use Case Dri'en Iterati$ns

In ter$s of use cases


9
ana!ysts define #ro+ect sco#e and #!an
9
ana!ysts deve!o# and va!idate architecture
9
deve!o#ers create the design < i$#!e$entation
$ode!s to rea!iAe use cases
9
testers define test cases and #rocedures
9
de#!oy$ent and docu$entation
CSIT5100
CSIT5100 2 scc
UML Views and Diagrams
Structural Dynamic
Static
view
Use case
view
Implementation
view
Deployment
view
State
machine
view
Activity
view
Interaction
view
Class
diagram
Use case
diagram
Component
diagram
Deployment
diagram
O!ect
diagram
Statec"art
diagram
Se#uence
diagram
Collaoration
diagram
Activity
diagram
CSIT5100 $ scc
Collaboration Diagram (Reminder)
:a!ment
Re"#est
UI
:$rder
%andler
:In&oi'e
(#!er
:a!ment
S')ed#ler
:$rder
Con*irmation
:a!ment
Re"#est
1:(rowse In&oi'e
+:(rowse
,:C)e'- In&oi'e
5:.et
/:.et
0:S')ed#le a!ment
1:setStat#s(s')ed#led)
2:3ew
4:S')ed#le in&oi'e
*or 5a!ment
S'enarios in Se"#en'e Diagrams
CSIT5100 5 scc
$b6e't Intera'tion

O!ects in t"e system


interact wit" eac"
ot"er y means o%
messages&

A message represents
a stimulus&

An interaction can e
reali'ed y invo(ing a
class met"od
)o"n *
+an( Operators
* Account Service
Re"3ew7''o#nt(3ame8999)
* Saving Accounts
Create Read! and Contin#e
De5osit C)e"#e
De5osit
CSIT5100 , scc
Intera'tion Diagrams

Two types o% diagrams


-
se#uence diagram

time ordered view point


-
collaoration diagram

may include data %low

more .condensed/ diagram


CSIT5100 0 scc
Use Case Des'ri5tion (:it)drawal)
1&1 1recondition* A user "as opened an account in t"e an(&
1&2 2low o% 3vents*
1 T"e AT4 as(s t"e user to insert a card5 t"e user inserts a cas" card&
2 T"e AT4 accepts t"e card and reads its serial numer&
$ T"e AT4 re#uests t"e 1I65 t"e user ;12$7<&
7 T"e AT4 veri%ies t"e serial numer and 1I6&
5 T"e AT4 as(s t"e user to select t"e (ind o% transaction5 t"e user selects
wit"drawal&
, T"e AT4 as(s %or t"e amount o% cas"5 t"e user enters 8100&
0 T"e AT4 veri%ies t"at t"e amount is wit"in prede%ined policy limits
9 T"e AT4 con%irms success and returns t"e new account alance&
: T"e AT4 dispenses cas" and as(s t"e user to ta(e it5 t"e user ta(es t"e cas"&
10T"e AT4 as(s w"et"er t"e user wants to continue5 t"e user indicates no&
11 T"e AT4 prints a receipt; e!ects t"e card; and as(s t"e user to ta(e t"em5 t"e
user ta(es t"e receipt and t"e card&
CSIT5100 9 scc
Sequence Diagram for ATM withdrawal
* User
* Cas"ier
Inter%ace
* <it"drawal * Cas" Card * Aut"ori'ation * Account * Dispenser
insert card
enter password
c"ec( card
c"ec( password
get aut"ori'ation
validate password
re#uest password
re#uest transaction
card o(
return aut"ori'ation
password o(
password o(
c"ec( card
card o(
CSIT5100 : scc
Se"#en'e Diagram (Cont9)
* User
* Cas"ier
Inter%ace
* <it"drawal * Cas" Card * Aut"ori'ation * Account * Dispenser
insert card
enter password
c"ec( card
c"ec( password
get aut"ori'ation
validate password
re#uest password
re#uest transaction
select transaction
select account
enter account
re#uest amount
enter amount
wit"draw
get accounts
get aut"ori'ed accounts
card o(
wit"draw
wit"draw o(
return accounts
return accounts
dispense cas"
transaction o(
ta(e cas" = card
cas" dispensed
return aut"ori'ation
password o(
password o(
* Cas"ier
Inter%ace
* <it"drawal * Cas" Card * Aut"ori'ation * Account * Dispenser
* User
CSIT5100 1$ scc
De*ining Met)ods in Class Diagram
<it"drawal
wit"draw>?
Trans%er
Deposit
Savings
rate
ase
addInterests>?
autotrans%er>?
Current
credit@imit
deduct>?
Credit Card
credit@imit
rate
getCredit@imit>?
getAate>?
Dispenser Cas"ier Inter%ace
Customer
Aut"ori'ation
c"ec(1assword>?
AT4
Account
accountB
alance
c"ec(alance>?
open>?
deposit>?
wit"draw>?
close>?
"old>?
C C C C
owns
Cas" Card
getAut"ori'ation>?
getAccounts>?
c"ec(Card>?
C
C
C
C
accesses
1 1 1 1
refers to
Transaction
Date
c"ec(Card>?
c"ec(1assword>?
getAccounts>?
1 C 1 C
performs
C
C
C
C
concerns
1
C
1
C
authorizes
CSIT5100 1, scc
Collaboration Diagrams

Anot"er type o% interaction diagrams

Collaoration diagrams s"ow


-
o!ects;
-
t"eir lin(s; and
-
t"eir messages&

3ac" collaoration diagram provides a view


o% t"e interactions and structural relations"ips
t"at occur etween o!ects&
CSIT5100 10 scc
7 'ollaboration diagram reali=ing t)e
a! In&oi'e Use Case
:a!ment
Re"#est
UI
:$rder
%andler
:In&oi'e
(#!er
:a!ment
S')ed#ler
:$rder
Con*irmation
:a!ment
Re"#est
1:(rowse In&oi'e
+:(rowse
,:C)e'- In&oi'e
5:.et
/:.et
0:S')ed#le a!ment
1:setStat#s(s')ed#led)
2:3ew
4:S')ed#le in&oi'e
*or 5a!ment
Seller:
7''o#nt
(#!er:
7''o#nt
CSIT5100 19 scc
Se"#en'e &s Collaboration

T"ey represent almost t"e same in%ormation

Could e converted %rom one to anot"er


automatically

Se#uence diagrams are etter %or understanding o%


time se#uence

Collaoration diagrams are etter %or s"owing lin(s


among o!ects
CSIT5100 1: scc
Str#'t#re $* Se"#en'e Diagrams
T"e application deals wit" a ware"ouse wit" automatic truc(s t"at
move pallets& A tec"nician gives an order speci%ying only w"ere a pallet
is to e moved to& All loads are placed on pallets t"at can e moved
around automatically in t"e ware"ouse& Since t"e pallets are moved
automatically; t"e loads must e c"ec(ed every tent" move at a
c"ec(ing station to ma(e sure t"at t"e loads are still stale on t"e
pallets& <e must t"ere%ore (eep trac( o% "ow many times a pallet "as
een moved&
What is the sequence diagram for this use case?
CSIT5100 20 scc
Str#'t#re $* Se"#en'e Diagrams
: Te')ni'ian
T)e te')ni'ian gi&es a
re"#est to mo&e
C)e'- i* t)e 5allet 'an be
mo&ed
I> ?mo&ed @ MaAMo&e?
T%B3 ')e'- i* mo&e is to
')e'-ing station
I> ')e'-ing station
T%B3 Mo&e
BLSB Mo&e not $C
B3DI>
BLSB
Mo&e
B3DI>
Case 1 Case 1
: allet : Trans5orter : :are)o#se
a'- D re"(5allet8dest)
?mo&esE
isF')e'-ingstation(dest)E
a'-
Go-H mo&e(dest)
im5li'it! im5lied
CSIT5100 21 scc
Str#'t#re $* Se"#en'e Diagrams
: Te')ni'ian
T)e te')ni'ian gi&es a
re"#est to mo&e
C)e'- i* t)e 5allet 'an be
mo&ed
I> ?mo&ed @ MaAMo&e?
T%B3 ')e'- i* mo&e is to
')e'-ing station
I> ')e'-ing station
T%B3 Mo&e
BLSB Mo&e not $C
B3DI>
BLSB
Mo&e
B3DI>
Case 2 Case 2
: allet : Trans5orter : :are)o#se
a'-Dre"(allet8Dest)
a'-Dmo&e(Dest)
isF')e'-ingstation(Dest)E
CSIT5100 22 scc
Str#'t#re $* Se"#en'e Diagrams
Consider now t"at we want to move painted icycles in t"e ware"ouse&
T"e i(es must not e moved until t"ey "ave dried %or siD "ours&
T"ere%ore; we must add a c"ec( on attriutes t"at (eep trac( o% w"et"er
t"ere is a painted i(e on t"e pallet and "ow long ago it was painted&
T"is latter attriute elongs to t"e i(e; ut must e c"ec(ed y 1allet&
What changes have to be made to the first sequence diagram?
1st Case: change both transporter and pallet
CSIT5100 2$ scc
Str#'t#re $* Se"#en'e Diagrams
Consider now t"at we want to move painted icycles in t"e ware"ouse&
T"e i(es must not e moved until t"ey "ave dried %or siD "ours&
T"ere%ore; we must add a c"ec( on attriutes t"at (eep trac( o% w"et"er
t"ere is a painted i(e on t"e pallet and "ow long ago it was painted&
T"is latter attriute elongs to t"e i(e; ut must e c"ec(ed y 1allet&
What changes have to be made to the second sequence diagram?
2nd Case: change only the pallet
CSIT5100 27 scc
Str#'t#re $* Se"#en'e Diagrams
or! diagram
"centrali#ed
control$
%
Stair diagram
"decentrali#ed
control$
CSIT5100 25 scc
Str#'t#re $* Se"#en'e Diagrams
or! diagram
"centrali#ed
control$
This structure is appropriate when:
- t"e operations can c"ange order
- new operations could e inserted
CSIT5100 2, scc
This structure is appropriate when:
- t"e operations "ave a strong connection
-
t"e operations will always e per%ormed in t"e same order
Str#'t#re $* Se"#en'e Diagrams
Stair diagram
"decentrali#ed
control$
CSIT5100 20 scc
Str#'t#re $* Se"#en'e Diagrams

A strong connection eDists among t"e operations


i% t"e o!ects*
-
%orm a ;consistsEo%< "ierarc"y; suc" as countryEstateEcity
-
%orm an in%ormation "ierarc"y; suc" as
documentEc"apterEsectionEparagrap"Ec"aracter
-
represent a %iDed temporal relations"ip suc" as
advertisementEorderEinvoiceEdeliveryEpayment
-
%orm a >conceptual? in"eritance "ierarc"y; suc" as
animalEmammalEcat
CSIT5100 29 scc
To s#mmari=e

<"at does an system analyst do at t"e re#uirement


analysis p"aseF

2or eac" use case;


- Use case partitioning

divide it up into oundary; entities and control classes

identi%y important interactions among t"ese classes


- Class analysis

identi%y class attriutes


- loo( at in%ormation supplied yGprovided to actors
- loo( at items manipulated in t"e use case
- loo( at in%ormation involved in t"e interactions among classes

identi%y associations %rom interaction diagrams

identi%y generali'ation %rom commonalties among classes


1
&eutral 'e(erse
Second Third irst
#5s)i*t
downs)i*t
#5s)i*t
downs)i*t
orward
5#s) 3
5#s) >
5#s) 3
5#s) R
Transmission
sto5
CSIT5100 $2 scc
SBCI>II3. $(JBCT (B%7VI$R K
$(JBCT ST7TBS
A A statechart diagram statechart diagram describes the behavior describes the behavior inside inside an object an object
(what an object does when it receives a message)
A A statechart diagram statechart diagram describes the behavior describes the behavior inside inside an object an object
(what an object does when it receives a message)

a statec"art diagram is a directed grap" t"at s"ows*


- t"e states o% a single o!ect >nodes?
- t"e events or messages t"at cause state c"anges >arcs?
- t"e actions t"at result %rom a state c"ange

s"ows all t"e messages t"at an o!ect can send and receive

descries all t"e possile states an o!ect can get into during its
li%e time

drawn %or a single class to s"ow t"e li%etime e"avior o% a single


o!ect
CSIT5100 $$ scc
7 ST7TBC%7RT DI7.R7M K (73C7CC$U3T
CL7SS
Initialize
InCredit Closed
Overdrawn
[balance>0] / set state=active
after(5 years)
[balance<0]
closeAccount /
set state=inactive
Frozen
[balance 0]
after(3 months)/
send BankManager.accountFrozen(account#)
[balance 0]
CSIT5100 $9 scc
C$M$SITB ST7TBC%7RT DI7.R7M
A A statechart diagram statechart diagram that has that has one one
or more nested statecharts or more nested statecharts
A A statechart diagram statechart diagram that has that has one one
or more nested statecharts or more nested statecharts
sequential composite statechart diagram
- o!ect is in eDactly one state in one o% t"e statec"art diagrams

corresponds to an orEcondition on all statec"art diagrams


- used to astractGgenerali'e states
concurrent composite statechart diagram
- o!ect is in eDactly one state in eac" o% t"e statec"art diagrams

corresponds to an andEcondition on all statec"art diagrams


- used to s"ow multiEt"reading e"avior
invoed b! " do G statec"artEdiagramEname >argumentElist?
CSIT5100 $: scc
SBLUB3TI7L C$M$SITB ST7TBC%7RT
DI7.R7M
Transmission
Neutral
Forward
Reverse
select R
select N
select F select N
CSIT5100 70 scc
Transmission
SBLUB3TI7L C$M$SITB ST7TBC%7RT
DI7.R7M
Neutral Reverse
select R
select N
select F select N
Second First Third
Forward
upshift upshift
downshift downshift
stop
superstate
substate
CSIT5100 71 scc
Result of Programming Assignment
Passed
Failed
Incomplete
fail
Result of Programming Assignment
Incomplete
Passed
Perform
tests
pass
Ask TA
for help
due date
done
Add
function
Deploy
patterns
done
Failed
C$3CURRB3T C$M$SITB
ST7TBC%7RT DI7.R7M

arises w"en an o!ect can e partitioned into susets o% attriutes or lin(s;


eac" wit" its own statec"art diagram
CSIT5100 7$ scc
C$3CURRB3T C$M$SITB ST7TBC%7RT
DI7.R7M K SI3C%R$3IM7TI$3
Concurrent state 1
A1 A2
B1 B2
Concurrent state 2
cleanup setup
synchronization bar
(fork)
synchronization bar
(join)
multiple
target
states
multiple
source
states
CSIT5100 77 scc
C$3CURRB3T C$M$SITB ST7TBC%7RT
DI7.R7M K SI3C%R$3IM7TI$3
Concurrent state 1
Example state
A1 A2
B1 B2
Concurrent state 2
cleanup setup
synchronization bar
(fork)
synchronization bar
(join)
multiple
target
states
multiple
source
states
>rom Se"#en'e Diagrams to State
Diagrams
CSIT5100 7, scc
Deri&ing State Diagrams

2rom Use Case


-
Se#uence o% events
-
Historical record o%
eDecuting a system
-
T"oug"t eDperiment
o% eDecuting a
proposed system
'aller li*ts re'ei&er
dial tone begins
'aller dials digit (5)
dial tone ends
'aller dials digit (5)
'aller dials digit (5)
'aller dials digit (1)
'aller dials digit (+)
'aller dials digit (,)
'aller dials digit (/)
'alled 5)one beings ringing
ringing tone a55ears in 'alling 5)one
'alled 5art! answers
'alled 5)one sto5s ringing
ringing tone disa55ears in 'alling 5)one
5)ones are 'onne'ted
'alled 5art! )angs #5
5)ones are dis'onne'ted
'aller )angs #5
CSIT5100 70 scc
Se"#en'e Diagram *or )one Call
:Caller :)hone *ine :Callee
'aller li*ts re'ei&er
dial tone begins
dial tone ends
dials (5)
dials (5)
dials (5)
dials (1)
dials (+)
dials (,)
dials (/)
5)one rings ringing tone
answers 5)one
ringing sto5s tone sto5s
5)ones 'onne'ted 5)ones 'onne'ted
'aller )angs #5
'allee )angs #5
'onne'tion bro-en 'onne'tion bro-en
CSIT5100 79 scc
State Diagram *or )one Line
+dle
Dial Tone
Dialing
Connecting
'inging
Connected
Disconnected
ast
busy tone
,usy tone
onN)oo-
digit(n)
n#mber b#s!
tr#n- b#s!
o**N)oo-
digit(n)
&alid n#mber
ro#ted
'alled 5)one answers
'alled 5)one )angs #5
'ecorded
message
Time-out
timeNo#t
timeNo#t
in&alid n#mber
onN)oo-
message
done
CSIT5100 7: scc
States8 B&ents and Timing

#vents represent points in


time

States represent intervals o%


time

State "as duration

State is associated wit"


continuous activity

An event separate two states

A state separate two events


:Caller :)hone *ine :Callee
caller lifts recei(er
dial tone begins
dial tone ends
dials ".$
dials ".$
dials ".$
dials "1$
dials "2$
dials "/$
dials "0$
phone rings ringing tone
answers phone
ringing stops tone stops
phones connected phones connected
caller hangs up
callee hangs up
connection bro!en connection bro!en
CSIT5100 50 scc
States8 B&ents and Timing
:Caller :)hone *ine :Callee
caller lifts recei(er
dial tone begins
dial tone ends
dials ".$
dials ".$
dials ".$
dials "1$
dials "2$
dials "/$
dials "0$
phone rings ringing tone
answers phone
ringing stops tone stops
phones connected phones connected
caller hangs up
callee hangs up
connection bro!en connection bro!en
CSIT5100 51 scc
State Diagram *or )one Line
+dle
Dial Tone
Dialing
Connecting
'inging
Connected
Disconnected
ast
busy tone
,usy tone
onN)oo-
digit(n)
n#mber b#s!
tr#n- b#s!
o**N)oo-
digit(n)
&alid n#mber
ro#ted
'alled 5)one answers
'alled 5)one )angs #5
'ecorded
message
Time-out
timeNo#t
timeNo#t
in&alid n#mber
onN)oo-
message
done
CSIT5100 52 scc
6ormal 2low o% 3vents
6ormal 2low o% 3vents
T)e 7TM as-s t)e #ser to insert a 'ardO t)e #ser inserts a 'as) 'ard9
T)e 7TM a''e5ts t)e 'ard and reads its serial n#mber9
T)e 7TM re"#ests t)e 5asswordO t)e #ser ;1+,/<9
T)e 7TM &eri*ies t)e serial n#mber and 5assword wit) t)e 'onsorti#mO t)e 'onsorti#m
')e'-s it wit) ban- ;,1< and noti*ies t)e 7TM a''e5tan'e9
T)e 7TM as-s t)e #ser to sele't t)e -ind o* transa'tion (wit)drawal8 de5osit8 trans*er8
"#er!)O t)e #ser sele'ts wit)drawal9
T)e 7TM as-s *or t)e amo#nt o* 'as)O t)e #ser enters P1009
T)e 7TM &eri*ies t)at t)e amo#nt is wit)in 5rede*ined 5oli'! limits and as-s t)e
'onsorti#m to 5ro'ess t)e transa'tionO t)e 'onsorti#m 5asses t)e re"#est to t)e ban-8
w)i') e&ent#all! 'on*irms s#''ess and ret#rns t)e new a''o#nt balan'e9
T)e 7TM dis5enses 'as) and as-s t)e #ser to ta-e itO t)e #ser ta-es t)e 'as)9
T)e 7TM as-s w)et)er t)e #ser wants to 'ontin#eO t)e #ser indi'ates no9
T)e 7TM 5rints a re'ei5t8 e6e'ts t)e 'ard8 and as-s t)e #ser to ta-e t)emO t)e #ser ta-es t)e
re'ei5t and t)e 'ard9
T)e 7TM as-s a #ser to insert a 'ard9
CSIT5100 5$ scc
3Dceptional 2low o% 3vents
3Dceptional 2low o% 3vents
T)e 7TM as-s t)e #ser to insert a 'ardO t)e #ser inserts a 'as) 'ard9
T)e 7TM swallows t)e 'ard and reads its serial n#mber9
T)e 7TM re"#ests t)e 5asswordO t)e #ser enters ;1111<9
T)e 7TM &eri*ies t)e serial n#mber and 5assword wit) t)e 'onsorti#m8 w)i')
re6e'ts it a*ter 'ons#lting t)e a55ro5riate ban-9
T)e 7TM indi'ates a bad 5assword and as-s t)e #ser to renter itO t)e #ser
enters ;1+,/< w)i') t)e 7TM s#''ess*#ll! &eri*ies wit) t)e 'onsorti#m9
T)e 7TM as-s t)e #ser to sele't t)e -ind o* transa'tionO t)e #ser sele'ts
wit)drawal9
T)e 7TM as-s *or t)e amo#nt o* 'as)O t)e #ser )as a ')ange o* mind and t)is
;'an'el<9
T)e 7TM e6e'ts t)e 'ard and as-s t)e #ser to ta-e itO t)e #ser ta-es it9
T)e 7TM as-s a #ser to insert a 'ard9
CSIT5100 57 scc
Sequence Diagram for ATM withdrawal
insert 'ard
User 7TM Transa'tion 7''o#nt
re"#est I3
enter I3
&eri*! a''o#nt
a#t)enti'ate
ban- a''o#nt $C
a''o#nt $C
re"#est -ind
enter -ind
re"#est amo#nt
enter amo#nt
5ro'ess transa'tion
wit)draw
wit)draw $C
transa'tion s#''eed
dis5ense 'as)
ta-e 'as)
re"#est ta-e 'as)
re"#est 'ontin#ation
terminate
re"#est ta-e 'ard
ta-e 'ard
e6e't 'ard
5rint re'ei5t
dis5la! main s'reen
CSIT5100 55 scc
State Diagram *or Class ATM
1ait for
networ!
response
+nterrupt
do:'an'elled
message
2nreadable
doQ#nreadable
'ard message
doQ*ail#re
message
cancel
doQ'an'elled
message
doQbad a''o#nt message
networ- res5onds
bad
5assword
'an'el
'an'el
insert 'ard
G#nreadableH
bad
a''o#nt
'an'el
'an'el
transa'tion
*ailed
'an'el
wait 5
se'onds
'ontin#e
a''o#nt $C
Main screen
doQre"#est insert
'ard
doQre"#est
5assword
doQ&eri*!
a''o#nt
Card e3ected
doQe6e't 'ardO
re"#est ta-e 'ard
inish
doQ5rint re'ei5t
doQre"#est
'ontin#ation
doQdis5ense 'as)O
re"#est ta-e 'as)
doQ5ro'ess
transa'tion
doQre"#est -ind
doQre"#est
amo#nt
insert 'ard
GreadableH
enter 5assword
ta-e
'ard
terminate 'an'el
ta-e 'as)
transa'tion
s#''eed
enter
amo#nt
enter
-ind
Main screen
doQre"#est insert
'ard
doQre"#est
5assword
doQ&eri*!
a''o#nt
Card e3ected
doQe6e't 'ardO
re"#est ta-e 'ard
inish
doQ5rint re'ei5t
doQre"#est
'ontin#ation
doQdis5ense 'as)O
re"#est ta-e 'as)
doQ5ro'ess
transa'tion
doQre"#est -ind
doQre"#est
amo#nt

CSIT5100 ,0 scc

T"ere are two types o%


implementation diagrams*
-
Component diagrams s"ow t"e structure o% t"e code
itsel%&
-
Deployment diagrams s"ow t"e structure o% t"e
runEtime system&
CSIT5100 ,9 scc
UML Views and Diagrams
Structural Dynamic
Static
view
Use case
view
Implementation
view
Deployment
view
State
machine
view
Activity
view
Interaction
view
Class
diagram
Use case
diagram
Component
diagram
Deployment
diagram
O!ect
diagram
Statec"art
diagram
Se#uence
diagram
Collaoration
diagram
Activity
diagram
Implementation
Diagrams
CSIT5100 ,: scc
:)at is a Com5onentE

A p"ysical implementation o% logical elements;


suc" as classes and interaction diagrams

O%ten maps to a %ile o% source code; inary code;


lirary; or eDecutale program

@i(e classes; components are types

Component instances reside on p"ysical nodes

6onidentity components E no identity; no state


-
all component instances produce identical results
-
e&g&; spell c"ec(er using a %iDed dictionary
CSIT5100 00 scc
Com5onents

Identity components "ave identity and states


-
di%%erent component instances may e"ave
di%%erently
-
e&g&; spell c"ec(er wit" customi'ale dictionary
and memory o% most recent re#uests

T"e inter%ace o% a component de%ines t"e


supported %unctionality

Components may e contained y anot"er


CSIT5100 01 scc
Com5onent

6otation
inter%aces
SpellEc"ec(
Synonyms
Dictionary
reali'ation
U4@ 1&D notation
CSIT5100 02 scc
Com5onent Diagram

To s"ow components organi'ation and t"eir


dependencies

Dependency can e due to compilation; runEtime;


in%ormation
CSIT5100 0$ scc
Com5onent Diagram
inde$%htm find%htm find%e$e
dbacs%dll
nateng%dll
IpageJ
IpageJ
IeDecutaleJ
IliraryJ IliraryJ
CSIT5100 07 scc
7TM
RR*ile@@
dis5enser9'
RR*ile@@
'lient9'
RReAe'#table@@
'lient9eAe
RR'om5ilation@@
CSIT5100 05 scc
Ti5s

A system may contain multiple component


diagrams

3ac" wellEstructured component diagram s"ould


%ocus on an implementation aspect o% a system;
e&g&;
-
one modeling dependencies among source codes
-
one modeling dependencies among eDecutales
-
one modeling dependencies among p"ysical dataase
tales
CSIT5100 0, scc
7d&an'ed 3otation (UML +90)
A component wit" two provided inter%aces and t"ree re#uired inter%aces
Order3ntry
+illing
CSIT5100 00 scc
BA5li'it Re5resentation o* ro&ided
and Re"#ired Inter*a'es wit) details
CSIT5100 0: scc
:)ite (oA Re5resentation
CSIT5100 90 scc
Internal Str#'t#re Re5resentation

CSIT5100 92 scc
De5lo!ment Diagram

S"ows t"e con%iguration o% p"ysical processing


nodes and t"e components t"at live on t"em

Consists o% nodes and connections


CSIT5100 9$ scc
7n Bmbedded S!stem
IprocessorJ
1entium
4ot"eroard
Timer
IIGO portJ
Serial AS2$2
IIGO portJ
1arallel
ImotorJ
Step 4otor
ImotorJ
Servo 4otor
IsensorJ
Ultrasonic Sensor
IsensorJ
1osition Sensor
CSIT5100 97 scc
7 3etwor-ed S!stem
*console
*console
*console
*Internet
*regional
server
*regional
server
*regional
server
*country
server
*logging
server
6ote* Country servers
are reac"ale to one
anot"er via t"e companyKs
private networ(
CSIT5100 95 scc
De5lo!ment Diagram
C$R(7
%TML (rowser
Client
II$ >irewalls
:eb Ser&ers
ser&lets
IntranetQ
InternetQ
BAtranet
7#t)ori=ation
Ser&er
999
C#stomer S#55orts :or-station
rimar!
Database
Ser&er
Se'ondar!
Database
Ser&er
755li'ation
Ser&er
CSIT5100 9, scc
7TM S!stem
*AT4
Client
*leased
lines
*AT4 Client
server
*AT4
Application
Server
*logging
server
*AT4
Client
*AT4
Client
*AT4
Data Server
:7TM
Inter*a'e
:7TM
Inter*a'e
:7TM
Inter*a'e
:7''o#nt
Management
Client
(an-
JD(C
Le&el /
(an-
C#stomer
:Transa'tion
Management

Notations in Class & Object Diagrams

Realization of an Interface

Package Notation

Template

Component and Node Notation

Collaboration Diagram

Seqence Diagram

State Diagram

State and !cti"it# Diagrams

Class Content

!ssociations $it% a Class Diagram

&eneralization in Class Diagrams

Icons in 'se Case Diagrams

'se Case Diagram Notations

Notations in !cti"it# Diagrams
CSIT5100
Program-based
Mutation Testing
S.C. Cheung
HKUST
Slides adapted from www.introsoftwaretesting.com by Paul Ammann & eff
!ffutt
May 8, 2014 CSIT5100 2
Program-/Code-based Mutation
Testing

The original and most widely "nown application of


synta#$based testing is to modify programs

!perators modify a ground string %program under


test& to create mutant programs

'utants %i.e.( mutant programs& must compile


correctly %)alid strings&

'utants are not tests( but used to find tests

!nce mutants are defined( tests must be found to


cause mutants to fail when e#ecuted

This is called *"illing mutants+

Killing of a mutant is a test re,uirement.


May 8, 2014 CSIT5100 3
-
Program-based Mutation Testing
Original Method
int Min (int A, int B)
{
int minVal;
minVal = A;
if (B < A)
{
minVal = B;
}
return (minVal);
} // end Min
With Embedded Mutants
int Min (int A, int B)
{
int minVal;
minVal = A;
1 minVal = B;
if (B < A)
2 if (B > A)
3 if (B < minVal)
{
minVal = B;
4 Bomb ();
5 minVal = A;
6 minVal = failOnZero (B);
}
return (minVal);
} // end Min
6 mutants
Each represents a
separate program
Replace one variable Replace one variable
with another with another
Changes operator Changes operator
Immediate runtime Immediate runtime
failure if reached failure if reached
Immediate runtime Immediate runtime
failure if B==0 else failure if B==0 else
does nothing does nothing
May 8, 2014 CSIT5100 4
i!!ing Mutants

If mutation operators are designed well, the resulting


tests will be very powerful

.ifferent operators must be defined for different programming


languages and goals

Testers can "eep adding tests until all mutants ha)e been
"illed

.ead mutant / A test case has "illed it

Stillborn mutant / Syntactically illegal

Tri)ial mutant / Almost e)ery test can "ill it

0,ui)alent mutant / 1o test can "ill it %e,ui)alent to original program&


Given a mutant m M for a (ground string) program
P and a test t, t is said to kill m if and only if the
output of t on P is different from the output of t on m
May 8, 2014 CSIT5100 5
Synta"-#ased Co$erage Criteria
Mutation !overage (M!) Mutation !overage (M!) " #or each " #or each m m M M, $% contains , $% contains
e&actly one re'uirement, to kill e&actly one re'uirement, to kill m m

$he %() model from *ecture +"

%eachability " $he test causes the faulty statement to be


reached (in mutation , the mutated statement)

(nfection " $he test causes the faulty statement to result in


an incorrect state

)ropagation " $he incorrect state propagates to incorrect


output

$he %() model leads to t-o variants of mutation coverage .


May 8, 2014 CSIT5100 %
Synta"-#ased Co$erage Criteria

+) /trongly 0illing Mutants"


Given a mutant m M for a program P and a test t, t is said to
strongly kill m if and only if the output of t on P is different
from the output of t on m

1) Weakly 0illing Mutants"


Given a mutant m M that modifies a location l in a program
P, and a test t, t is said to -eakly kill m if and only if the
state of the e&ecution of P on t is different from the state of the
e&ecution of m immediately on t after l

Weakly killing satisfies reachability and infection, but not


propagation
May 8, 2014 CSIT5100 &
'ea( Mutation
Weak Mutation !overage (WM!) Weak Mutation !overage (WM!) " #or each " #or each m m M M, $% , $%
contains e&actly one re'uirement, to -eakly kill contains e&actly one re'uirement, to -eakly kill m m

2Weak mutation3 is so named because it is easier to kill


mutants under this assumption

Weak mutation also re'uires less analysis

/ome mutants can be killed under -eak mutation but not


under strong mutation (no propagation)

(n practice, there is little difference


May 8, 2014 CSIT5100 8
'ea( Mutation )"am*!e

'utant 2 in the 'in% & e#ample is/

$he complete test specification to kill mutant +"

%eachability " true 44 5l-ays get to that statement

(nfection " A B

)ropagation" !B " A# = false 44 /kip the ne&t assignment

#ull $est /pecification " true !A B# !!B " A# = false#


$ !A B# !B %A#
$ !B & A#

(5 6 7, 8 6 9) -ill -eakly kill mutant +, but not strongly


minVal = A;
1 minVal = B;
if (B < A)
minVal = B;
Original Method
int Min (int A, int B)
{
int minVal;
minVal = A;
if (B < A)
minVal = B;
return (minVal);
} // end Min
Mutant
int Min (int A, int B)
{
int minVal;
minVal = B;
if (B < A)
minVal = B;

return (minVal);
} // end Min
May 8, 2014 CSIT5100 +
),ui$a!ent Mutation )"am*!e

'utant - in the 'in%& e#ample is e,ui)alent/


minVal = A;
if (B < A)
3 if (B < minVal)

$he infection condition is 2(8 : 5) ;6 (8 : min<al)3

=o-ever, the previous statement -as 2min<al 6 53

/ubstituing, -e get" 2(8 : 5) ;6 (8 : 5)3

$hus no input can kill this mutant


Original Method
int Min (int A, int B)
{
int minVal;
minVal = A;
if (B < A)
minVal = B;
return (minVal);
} // end Min
Mutant
int Min (int A, int B)
{
int minVal;
minVal = A;
if (B < minVal)
minVal = B;

return (minVal);
} // end Min
May 8, 2014 CSIT5100 10
23
Strong -ersus 'ea( Mutation
1 boolean isEven (int X)
2 {
3 if (X < 0)
4 X = 0 - X;
4 X = 0;
5 if (float) (X/2) == ((float) X) / 2.0
6 return (true);
7 else
8 return (false);
9 }
%eachability %eachability " > : ? " > : ?
(nfection (nfection " > ;6 ? " > ;6 ?
(> 6 @6) -ill kill mutant (> 6 @6) -ill kill mutant
A under A under -eak mutation -eak mutation
)ropagation )ropagation " "
((float) ((?@>)41) 66 ((float) ?@>) 4 1?) ((float) ((?@>)41) 66 ((float) ?@>) 4 1?)
;6 ((float) (?41) 66 ((float) ?) 4 1?) ;6 ((float) (?41) 66 ((float) ?) 4 1?)
$hat is, > is $hat is, > is not not even . even .
$hus (> 6 @6) does $hus (> 6 @6) does not not kill the mutant kill the mutant
under strong mutation under strong mutation
May 8, 2014 CSIT5100 11
5utomated 5utomated
steps steps
Testing Programs .it/
Mutation
(nput test
method
)rog ) !reate
mutants
%un $
on )
%un mutants"

-eak

selective
Eliminate
ineffective
$!s
Generate
test cases
%un
e'uivalence
detector
$hreshold
reached
B
Cefine
coverage
threshold
no
) ($)
correct
B
'es
#i&
)
no
May 8, 2014 CSIT5100 12
'/y Mutation 'or(s

This is not an absolute 4

The mutants guide the tester to a )ery effecti)e set of


tests

A )ery challenging problem /

5ind a fault and a set of mutation$ade,uate tests that do not find


the fault

!f course( this depends on the mutation operators 6


#undamental )remise of Mutation $esting
#undamental )remise of Mutation $esting
(f the soft-are contains a fault, there -ill
(f the soft-are contains a fault, there -ill
usually be a set of mutants that can only be
usually be a set of mutants that can only be
killed by a test case that also detects that fault
killed by a test case that also detects that fault
May 8, 2014 CSIT5100 13
Subsum*tion o0 1t/er Criteria

'utation is widely considered the strongest test criterion

And most e#pensi)e 4

'utation subsumes other criteria by including specific


mutation operators

Subsumption actually only ma"es sense for wea" mutation 7


other criteria impose local re,uirements( li"e wea" mutation

1ode co)erage

0dge co)erage

Clause co)erage

8eneral acti)e clause co)erage

Correlated acti)e clause co)erage

All$defs data flow co)erage


May 8, 2014 CSIT5100 14
Mutation Testing

The number of test re,uirements for mutation


depends on two things

The synta# of the artifact being mutated

The mutation operators

'utation testing is )ery difficult to apply by


hand

'utation testing is )ery effecti)e 7 considered


the *gold standard+ of testing

'utation testing is often used to e)aluate


other criteria
MUTATION OPERATORS
5or reference only %not e#amined&
May 8, 2014 CSIT5100 15
May 8, 2014 CSIT5100 1%
2esigning Mutation 1*erators

At the method le)el( mutation operators for different


programming languages are similar

'utation operators do one of two things/

'imic typical programmer mista"es % incorrect )ariable name &

0ncourage common test heuristics % cause e#pressions to be 3 &

9esearchers design lots of operators( then e#perimentally


select the most useful
Effective Mutation Operators Effective Mutation Operators
(f tests that are created specifically to kill mutants created (f tests that are created specifically to kill mutants created
by a collection of mutation operators by a collection of mutation operators ( ( 6 D 6 Do)* o+* o)* o+* .E also .E also
kill mutants created by all remaining mutation operators kill mutants created by all remaining mutation operators
-ith very high probability, then -ith very high probability, then ( ( defines an effective set of defines an effective set of
mutation operators mutation operators
May 8, 2014 CSIT5100 1&
Mutation 1*erators 0or 3a$a
Each occurrence of one of the arithmetic operators +, ,*, , and % is
replaced by each of the other operators. In addition, each is replaced by the
special mutation operators leftOp, and rightOp.
2. AOR Arithmetic Operator Replacement:
Each arithmetic expression (and subexpression) is modified by the functions
abs(), negAbs(), and failOnZero().
1. ABS Absolte !ale "nsertion#
Each occurrence of one of the relational operators (, !, ", #, $, %) is replaced
by each of the other operators and by false&p and true&p.
$. ROR Relational Operator Replacement#
May 8, 2014 CSIT5100 18
Mutation 1*erators 0or 3a$a
425
Each occurrence of one of the lo'ical operators (and ( )), or ( ** , and +ith no
conditional e,aluation ( ), or +ith no conditional e,aluation ( *, not e-ui,alent
( .) is replaced by each of the other operators/ in addition, each is replaced by
false&p, true&p, left&p, and ri'ht&p.
%. &OR &on'itional Operator Replacement#
(. SOR Shift Operator Replacement#
Each occurrence of one of the shift operators , "", and """ is replaced by
each of the other operators. In addition, each is replaced by the special
mutation operator left&p.
Each occurrence of one of the lo'ical operators (bit+ise and ( ), bit+ise or
( *, exclusi,e or ( .) is replaced by each of the other operators/ in addition,
each is replaced by left&p and ri'ht&p.
). *OR *ogical Operator Replacement#
May 8, 2014 CSIT5100 1+
Mutation 1*erators 0or 3a$a
435
Each occurrence of one of the assi'nment operators (+$, ($, 0$, 1$, %$, )$,
*$, .$, $, ""$, """$) is replaced by each of the other operators.
+. ASR Assignment Operator Replacement#
,. -O" -nar. Operator "nsertion#
Each unary operator (arithmetic +, arithmetic (, conditional 2, lo'ical 3) is
inserted in front of each expression of the correct type.
Each unary operator (arithmetic +, arithmetic (, conditional 2, lo'ical3) is
deleted.
/. -O0 -nar. Operator 0eletion#
May 8, 2014 CSIT5100 20
Mutation 1*erators 0or 3a$a
Each ,ariable reference is replaced by e,ery other ,ariable of the appropriate
type that is declared in the current scope.
11. S!R Scalar !ariable Replacement#
11. BSR Bomb Statement Replacement#
Each statement is replaced by a special 4omb() function.
CSIT5100
Object-Oriented
Testing
S.C. Cheung
HKUST
Slides adapted from www.introsoftwaretesting.com by Paul Ammann & eff
!ffutt
May 8, 2014 CSIT5100 2
Outline

!"er"iew

!b#ect$!riented %aults

&'ample

The (o$(o )raph and Polymorphism

Categories of *nheritance %aults

Testing *nheritance+ Polymorphism and ,ynamic


-inding
May 8, 2014 CSIT5100 3
Ineritance

&nhance deri"ed features .o"erriding/

0estrict deri"ed features

Add new features .e'tension/


A derived class has everything
its parent has, plus it can:
Allows common features of many
classes to be defined in one class
May 8, 2014 CSIT5100 4
Ineritance !2"
Declared type: The type given when an object
reference is declared
Clock w1; // declared type Clock
Actual type: The type of the current object
w1 = new Watch(); // actual type Watch
1
#$a%&le '( )airs and
*n+%alies
B
+h ()
+i ()
+k ()
-x
A
-u
-v
-w
+h()
+i()
+j()
+l()
C
+i ()
+j ()
+l ()
-y
Method Defs Uses
A::h ( !A::u, A::w"
A::i ( !A::u"
A::j ( !A::v" !A::w"
A::l( !A::v"
#::h( !#::$"
#::i( !#::$"
%::i(
%::j( !%::y" !%::y"
%::l( !A::v"
%onsider what happens when an
overriding method has a different
def&set from that of its overridden
method
def&use
def&use
DU
anomaly
DU
anomaly
void f(A o !
o'h(( o'i((
o'j(( o'l((
"
A::h( assumes calling
j( later( #::h( does
not assume so
May 8, 2014 CSIT5100 ,
)+ly%+r&is% -isuali.ati+n !/+-/+
0ra&"
A
+d ()
+g ()
+h ()
+i ()
+j ()
+l ()
Instantiated
type
B
k() h() i()
C j() i() l()
A d() j() g() h() i() l()
Object is of type A
A::d ()
)+ly%+r&is% 1eadaces
!/+-/+"
A
+d ()
+g ()
+h ()
+i ()
+j ()
+l ()
B
+h ()
+i ()
+k ()
B h() i() k()
Instantiated
type
B
k() h() i()
C j() i() l()
A d() j() g() h() i() l()
C j() i() l()
A d() j() g() h() i() l()
Object is of type B
B::d ()
Data flow anomaly of A::w occurs at the call of A::j(
Data flow anomaly of A::u occurs at the call of A::i(
)ote: A::i( and A::j( need to be re&tested in view of # even they have
been tested to be correct under A*
void i( ! super'i(( + "
May 8, 2014 CSIT5100 8
)+ly%+r&is% 1eadaces !/+-/+"
A
+d ()
+g ()
+h ()
+i ()
+j ()
+l ()
B
+h ()
+i ()
+k ()
C
+i ()
+j ()
+l ()
C j() i() l()
B h() i() k()
Instantiated
type
B
k() h() i()
C j() i() l()
A d() j() g() h() i() l()
C j() i() l()
A d() j() g() h() i() l()
B h() i()
k()
A d() j() g() h() i() l()
Data flow anomaly of A::v occurs at the call of %::l(
C+%%+n Ineritance
2aults
May 8, 2014 CSIT5100 10 23
Causes +3 2aults in OO
)r+gra%s

Comple'ity is relocated to the connections


among components

,ess static determinism - many faults can now only


be detected at runtime

.nheritance and /olymorphism yield vertical and


dynamic integration

Aggregation and use relationships are more comple$

Designers do not carefully consider visibility of data


and methods
May 8, 2014 CSIT5100 11
Object-+riented 2aults

!nly consider faults that arise as a direct


result of !! language features4

inheritance

polymorphism

constructors

"isibility

5anguage independent .as much as


possible/
May 8, 2014 CSIT5100 12
Inc+nsistent Ty&e (se !IT("

6o o"erriding methods .no polymorphism/

C e'tends T+ and C adds new methods .e'tension/

An ob#ect is used 7as a C8+ then as a T+ then as a C

9ethods in T can put ob#ect in state that is inconsistent


for C
Vector
-array
+insertElementAt()
+removeElementAt()
Stack
+pop (): Object
+push (): Object
call
call
class Stack extens Vector !
public int count " #$
public Object pop( ) !
--count$
return super%removeElementAt( )$
&
public Object push( ) !
++count$
return super%insertElementAt( )$
&
&
May 8, 2014 CSIT5100 13
Inc+nsistent Ty&e (se !IT("

6o o"erriding methods .no polymorphism/

C e'tends T+ and C adds new methods .e'tension/

An ob#ect is used 7as a C8+ then as a T+ then as a C

9ethods in T can put ob#ect in state that is inconsistent


for C
Vector
-array
+insertElementAt()
+removeElementAt()
Stack
+pop (): Object
+push (): Object
call
call
'' Stack is empty(
s%push ()Ste**i+)$
s%push (),oyce+)$
s%push ()Anre-+)$
umb (s)$
s%pop()$
s%pop()$
s%pop()$
voi umb (Vector v) !
v%removeElementAt (v%si.e()-/)$
&
A 0 1
State 'e4niti+n *n+%aly
!S'*"

Y e'tends W+ and Y o"errides some methods

The o"erriding methods in Y fail to define some


"ariables that the o"erridden methods in W defined
0
v
u
m()
n()
1
x
n()
2
-
m()

W::m () defines v and W::n() uses v

X::n () uses v

Y::m () does not define v


2or an object of type Y, a data flow anomaly
of v e$ists and results in a fault if m() is called,
then n()
)ote that it wor3s for objects of type 4' This
suggests that testing 5::m( alone in regression
testing is inade6uate'
void f(7 o !
o'm((
o'n((
"
21
State 'e4niti+n Inc+nsistency
!S'I1"

Hiding a "ariable+ possibly accidentally

*f the descendant:s "ersion of the "ariable is defined+ the


ancestor:s "ersion may not be
0
v
u
m()
n()
1
x
n()
2
v
m()

Y hides W8s version of v

Y::m() defines Y::v

X::n() uses v
2or an object of type Y, a data flow
inconsistency of v may e$ist and result in a
fault if m() is called, then n()
void f(7 o !
o'm((
o'n((
"
May 8, 2014 CSIT5100 1,
*n+%al+us C+nstructi+n 5ea6i+r
!*C51"

Constructor of W calls a method f()

A child of W+ X+ o"errides f()

X::f() uses "ariables that should be defined by X:s


constructor
0
0()
*()
1
v
*()
%alls
Uses
9verrides
7hen an object of type X is constructed,
W() is run before X()'
7hen W() calls X::f(), v is used, but has
not yet been given a value*
2;
State -isibility *n+%aly !S-*"

A pri"ate "ariable v is declared in ancestor W+ and v


is defined by W::m()

X e'tends W and Y e'tends X

Y o"errides m()+ and calls W::m() to define v


0
-v
m()
1
2
m()
9verrides,
calls
0
-v
m()
1
m()
2
m()
9verrides,
calls
9verrides
X::m() is added later
Y:m() can no longer call W::m()
directly, and has no direct control
over the dataflow anomaly of v'
Ma3e such edge pair a test
re6uirement'
super'm((
May 8, 2014 CSIT5100 18
C+nclusi+ns

A model for understanding and analy<ing faults


that occur as a result of inheritance and
polymorphism

Techni=ue for identifying data flow anomalies in


class hierarchies

Please refer to Ammann & !ffutt Chapter ; for details

A fault model and specific faults that are common


in !! software

!ther challenges include4

Testing >eb applications and >eb ser"ices

Testing real$time and embedded software


Automated Software
Testing
Supplementary Materials
Automatic Software Testing

Random testing

Symbolic testing

Concolic testing
Random Testing
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}
try 1: x = 0, y = 0;
try 2: x = 0, y = 1
...
try n: x = 1, y = 0
Random inut data
generation
Random user intera!tion
se"uen!e
Random data sele!tion from
database
#ombinations of all abo$e
Random Testing

Mentioned frst time by Glenford J. Myers in 1!.


"opularly used by industry as fu##ing tests.
Automatic Software Testing

Random testing

Symbolic testing

Concolic testing
Symbolic Testing $a.%.a. Symbolic
&'ecution(

)ey idea* e'ecute programs


using symbolic input +alues
instead of concrete
e'ecution

Concrete e'ecution ',-.


y,1
Symbolic e'ecution ',a.
y,b
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}
Adapted from /ttp*00www.#+onimir.info0teac/ing0s+12-121fall0s+3lecture311.pdf
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
Symbolic Testing $a.%.a. Symbolic
&'ecution(
foo (int x, int y) {
if (x>y) {
x = x + y;
y = x - y;
x = x - y;
if (x - y > 0) {
assert (false); // bug
}
}
}

Constraints*
a4b 55 b1a4-
[ a < = b ] E N D
[ a > b , b - a < = 0 ] E N D [ a > b , b - a > 0 ] f a i l
[ a > b ] b - a > ? 0
[ a > b ] x = ( a + b ) - a = b
[ a > b ] y = ( a + b ) - b = a
[ a > b ] x = a + b
a < ? b
x = a , y = b
6sing a %inear Constraint Sol+er
a4b 55 b1a4-
&7cient linear constraint sol+ers are a+ailable
Constraint Sol+ing wit/ 8/at1if
Analysis
b1a4-
a , -. b , 1
Automatic Software Testing

Random testing

Symbolic testing

Concolic testing
)ous/i% Sen
&sso!iate 'rofessor, (# )er*eley
Resear!+ &reas
"rogramming Systems. Software &ngineering.
"rogramming 9anguages. and :ormal Met/ods*
Software Testing. ;erifcation. Model C/ec%ing.
Runtime Monitoring. "erformance &+aluation. and
Computational 9ogic
Security
Concolic , Concrete < Symbolic
inputs of ' and y=
A concrete
e'ecution
in+ol+e e'ternal
or non1linear
function calls

' , 1>. y ,1-


:ailure point
call f$?(
Concolic , Concrete < Symbolic
int foo$int '. int y( @
int # , sAuare$'(B
if $# 4 1-- 55 y 4 2-(
assert$false(B
return yC#B
D
Test* foo$1>. 1-(
' , 1>. y , 1-
# , 22>
22> 4 1-- 55 1- 4 2-
return 22>-
Execute program concretely
Concolic , Concrete < Symbolic
int foo$int '. int y( @
int # , sAuare$'(B
if $# 4 1-- 55 y 4 2-(
assert$false(B
return yC#B
D
Test* foo$1>. 1-(
' , 1>. y , 1-
# , 22>
22> 4 1-- 55 1- 4 2-
return E>--
Execute program concretely
Collect symbolic path condition
' , F. y , G
# , sAuare$F(
=$sAuare$F( 4 1-- 55 G 4 2-(
HI$sAuare$F( 4 1--
55 G 4 2-(J
return GCsAuare$F(
Concolic Testing
int foo$int '. int y( @
int # , sAuare$'(B
if $# 4 1-- 55 y 4 2-(
assert$false(B
return yC#B
D
Test* foo$1>. 1-(
' , 1>. y , 1-
# , 22>
22> 4 1-- 55 1- 4 2-
return E>--
' , F. y , G
# , sAuare$F(
=$sAuare$F( 4 1-- 55 G 4 2-(
HI$sAuare$F( 4 1--
55 G 4 2-(J
return GCsAuare$F(
HsAuare$F( 4 1--. G 4 2-J
Execute program concretely
Collect symbolic path condition
Negate a constraint on the path condition and solve it
Concolic Testing
int foo$int '. int y( @
int # , sAuare$'(B
if $# 4 1-- 55 y 4 2-(
assert$false(B
return yC#B
D
Test* foo$1>. 1-(
' , 1>. y , 1-
# , 22>
22> 4 1-- 55 1- 4 2-
return E>--
' , F. y , G
# , sAuare$F(
=$sAuare$F( 4 1-- 55 G 4 2-(
HI$sAuare$F( 4 1--
55 G 4 2-(J
return GCsAuare$F(
H22> 4 1--. G 4 2-J
assert$ false (
Design Patterns
- Design Reuse
What are Design Patterns?
Learning Objective:

To know what design patterns are


GoFs 23 Design
Patterns
Learning Objective:

To overview GoFs 23 design patterns


CSIT!"" # scc
A List of 23 Design Patterns

$ehaviora% &atterns '!!(


)
Chain o* +esponsibi%ities
)
Co,,and Interpreter
)
Iterator -ediator
)
-e,ento Observer
)
State Strateg.
)
Te,p%ate -ethod /isitor
CSIT!"" scc
A List of 23 Design Patterns

Creationa% &atterns '(


)
0bstract Factor. $1i%der
)
Factor. -ethod &rotot.pe
)
Sing%eton

Str1ct1ra% &atterns '2(


)
0dapter $ridge
)
Co,posite 3ecorator
)
Fa4ade F%.weight
)
&ro5.
CSIT!"" 6 scc
Structure Of The Observer Pattern
77abstract88
S1bject
attach'Observer(
detach'Observer(
noti*.' (
77abstract88
Observer
1pdate' (

For a%% o in observers 9
o:1pdate' (
;
observers
! <
ConcreteS1bject
s1bjectState
getState' (
setState' s (
ConcreteObserver
observerState
1pdate' (
observerState =
s1bject:getState' (
ret1rn s1bjectState
s1bject
< !
s1bjectState = s
noti*.'(
CSIT!"" 2 scc
o!!aboration Of The Observer Pattern
:ConreteS1bject :ConcreteObserver
setState'
(
getState' (
1pdate' (
noti*.' (
:ConcreteObserver
1pdate' (
getState' (
CSIT!"" > scc
D"S#G$ PATT"R$% S#$GL"TO$ &
'OT#(AT#O$
Problem: It is i,portant *or so,e c%asses to have e5act%. one instance:
?ow to ens1re that a c%ass has on%. one instance and that the
instance is easi%. accessib%e@
e:g:A a%tho1gh there can be ,an. printers in a s.ste,A there
sho1%d be on%. one print spoo%er
0 g%oba% variab%e can ,ake an object accessib%eA b1t how to prohibit
instantiation o* ,1%tip%e instances@
Solution: -ake the sing%eton c%ass itse%* responsib%e *or
) keeping track o* its so%e instance
) ens1ring that no other instance can be createdA and
) providing a wa. to access the instance
CSIT!"" !" scc
D"S#G$ PATT"R$% S#$GL"TO$
Singleton ) de*ines an Instance operation that %ets c%ients access its 1niB1e
instance: Instance is a c%ass operation:
) ,a. be responsib%e *or creating its own 1niB1e instance:
if (self is NULL)
self = new Singleton
return self
Singleton
self : Singleton
singletonData
instance()
singletonOperation()
getSingletonData
.
.
.
Singleton::instance()singletonOperation();
.
.
.
Client
anOperation()
CSIT!"" !! scc
GoFs Abstract Factor) Patterns

&rovide an inter*ace *or creating *a,i%ies o* re%ated or


dependent objects witho1t speci*.ing their concrete
c%asses

For si,p%er casesA ,a. 1se concrete *actor. instead


CSIT!"" !2 scc
GoFs Abstract Factor) Patterns
77inter*ace88
0bstract Factor.

create&rod1ct0' (
create&rod1ct$' (
C%ient
77inter*ace88
0bstract&rod1ct0
77inter*ace88
0bstract&rod1ct$
1ses
1ses
1ses
!
!
<
<
!
!
ConcreteFactor.2

create&rod1ct0' (
create&rod1ct$' (
&rod1ct02
&rod1ct$2
creates
creates
!
<
<
<
<
ConcreteFactor.!

create&rod1ct0' (
create&rod1ct$' (
&rod1ct0!
&rod1ct$!
creates
creates
!
CSIT!"" !3 scc
GoFs o*+osite Patterns

Co,pose objects into tree str1ct1re to represent


partCwho%e hierarchies
77abstract88
Co,ponent
operation' (
add'Co,ponent(
re,ove'Co,ponent(
getChi%d'int(
Co,posite
operation' (
add'Co,ponent(
re,ove'Co,ponent(
getChi%d'int(
Lea*
operation' (
C%ient
chi%dren
<
CSIT!"" !# scc
GoFs A,a+ter Patterns

Convert the inter*ace o* a c%ass into another instance


C%ient
77inter*ace88
Target

reB1est' (
0dapter

reB1est' (
0daptee

speci*ic+eB1est' (
adaptee
!
!
! !::<
adaptee:speci*ic+eB1est' (
CSIT!"" ! scc
GoFs Strateg) Patterns

3e*ine a *a,i%. o* a%gorith,sA encaps1%ate each oneA


and ,ake the, interchangeab%e
77inter*ace88
Strateg.

a%gorith,Inter*ace' (
ConcreteStrateg.0
a%gorith,Inter*ace' (
ConcreteStrateg.$
a%gorith,Inter*ace' (
ConcreteStrateg.C
a%gorith,Inter*ace' (
Conte5t
conte5tInter*ace' (
CSIT!"" !6 scc
So*e Other Patterns

So,e patterns %isted in D&atterns in EavaF


)
Object &oo% /irt1a% &ro5.
)
G1%% Object Sched1%er
)
&rod1cerCCons1,er +eadHIrite Lock

So,e patterns in DCore E2JJ &atternsF


)
Intercepting Fi%ter /iew ?e%per
)
Service to Iorker $1siness 3e%egate
)
Session Facade Service 0ctivator
ase Stu,)
CSIT!"" !> scc
A POS s)ste*

S1ppose we are deve%oping a pointCo*Csa%e '&OS(


s.ste, that wi%% be so%d to di**erent c%ients with
disparate needs
)
It records sa%es and hand%e pa.,ents
)
It is t.pica%%. 1sed in a retai% store
)
It inter*aces to other services app%ications

J:g: Ta5 ca%c1%atorA inventor. contro%A K etc:


)
It s1pports varied c%ientCside inter*aces
CSIT!"" !L scc
A POS s)ste*

Given the concept1a% ,ode%


InitiatedCb.
+ecordCsa%esCon
Cashier
!
!
C1sto,er
!
&a.,ent
!
&aidCb.
InitiatedCb.
Capt1redCon
LogsCco,p%e
ted
ContainedCin
?o1ses
StartCb.
-anager
!
Stocks
&rod1ct Cata%og
!
!
&rod1ct Speci*ication
!
!::<
Sa%es LineIte,
<
"::!
!::<
3escribedCb.
+ecordCsa%eCo*
Ite,
< <
<
3escribes
+egister
!
!::<
!
!
Store
! !
!
<
MsedCb.
Sa%e
!
!
!
<
!
!
Contains
CSIT!"" 2" scc
First Design #ssue

The &OS s.ste, needs to s1pport severa% e5terna%


3
rd
Cpart. services
)
J:g: Ta5 ca%c1%atorsA credit a1thoriNation
inventor. s.ste,sA acco1nting s.ste,
)
Jach has di**erent 0&I
)
The 0&I cannot be change

Ihat pattern's( ,ight he%p@ 0nd how@


CSIT!"" 2! scc
First Design #ssue

0ss1,e we are working with the ta5 ca%c1%ator


)
3raw a c%ass diagra, *or on%. the new
c%asses that rea%iNe the pattern's(
)
3raw a seB1ence diagra, to show how the
new c%ass'es( work with the origina%
c%ass'es(
CSIT!"" 22 scc
First Design #ssue -Ans.er/

0dapter pattern ,ight he%p


)
0dd a %eve% o* indirection with objects that
adapt the var.ing e5terna% inter*aces to a
consistent inter*ace 1sed within the
app%ication
CSIT!"" 23 scc
First Design #ssue -Ans.er/

C%ass diagra, *or the 1sing the adapter pattern with


the ta5 ca%c1%ator e5terna% service
77inter*ace88
Ta5Ca%c1%ator0dapter

getTa5es'Sa%e( : List o* Ta5LineIte,s
Ta5-aster0dapter

getTa5es'Sa%e( : List o* Ta5LineIte,s
StateTa50dapter

getTa5es'Sa%e( : List o* Ta5LineIte,s
CSIT!"" 2# scc
re,ote
co,,1nication
First Design #ssue -Ans.er/

SeB1ence diagra, to show how to 1se the adapter


77s.ste,88
:Ta5Ca%c1%ator
:+egister :Ta5-aster0dapter
,ake&a.,ent'
(
origina% seB1encesK
postSa%e' sa%e (
Ta5Ca%c1%ator0dapter
CSIT!"" 2 scc
Secon, Design #ssue

In the prior pattern so%1tion *or e5terna% services with


var.ing inter*acesA prob%e, raises
)
Iho creates the new 0dapter objects@
)
?ow to deter,ine which s1bc%ass'es( to
create@

I* so,e do,ain objects create the,A the


responsibi%ities o* the do,ain objects go be.ond p1re
app%ication %ogic
CSIT!"" 26 scc
Secon, Design #ssue

0n architect1ra% design princip%e


)
3esign to ,aintain a separation o*
concerns
)
&robab%. we sho1%d add new s.ste,
object's(

Ihat pattern's( ,ight he%p@


)
0dd it to the c%ass diagra,
Aspect-oriented programming is a
recent research effort made to
address the separation of concerns
Aspect-oriented programming is a
recent research effort made to
address the separation of concerns
CSIT!"" 22 scc
Secon, Design #ssue -Ans.er/

-a. app%. the Factor. 'or Concrete Factor.( patternA


in which a &1re Fabrication D*actor.F object is de*ined
to create objects
ServicesFactor.
acco1nting0dapter : 0cco1nting0dapter
inventor.0dapter : Inventor.0dapter
ta5Ca%c1%ator0dapter : Ta5Ca%c1%ator0dapter
get0cco1nting0dapter' ( : 0cco1nting0dapter
getInventor.0dapter' ( : Inventor.0dapter
getTa5Ca%c1%ator0dapter' ( : Ta5Ca%c1%ator0dapter
Gote that the *actor.
,ethods ret1rn objects
t.ped to an inter*ace
rather than to a c%ass
CSIT!"" 2> scc
Thir, Design #ssue

0nother prob%e, in the design raises


)
Iho creates the new c%ass'es( added in
second design iss1e@
)
?ow is it accessed@

So,e observation
)
See,s on%. one instance o* the new
s.ste, object is needed
)
Its ,ethods ,a. need to be ca%%ed *ro,
vario1s p%aces in the code
CSIT!"" 2L scc
Thir, Design #ssue

To the visibi%it. prob%e,


)
One so%1tion is to pass its instance aro1nd as
a para,eter to wherever a visibi%it. need is
discovered *or it
)
Or initia%iNe the objects that need visibi%it. to it
with a per,anent re*erence

Ihat pattern's( ,ight be an a%ternative@


)
0dd its s1pport to the c%ass diagra,
CSIT!"" 3" scc
instance : ServiceFactor.
acco1nting0dapter : 0cco1nting0dapter
inventor.0dapter : Inventor.0dapter
ta5Ca%c1%ator0dapter : Ta5Ca%c1%ator0dapter
getInstance' ( : ServicesFactor.
get0cco1nting0dapter' ( : 0cco1nting0dapter
getInventor.0dapter' ( : Inventor.0dapter
getTa5Ca%c1%ator0dapter' ( : Ta5Ca%c1%ator0dapter
ServicesFactor.
!
Thir, Design #ssue -Ans.er/

0n a%ternative is the Sing%eton pattern


)
It is desirab%e *or the ServicesFactor.
instance to s1pport g%oba% visibi%it. and a
sing%e access point to a singe instance
sing%eton static ,ethod
sing%eton static attrib1te
CSIT!"" 3! scc
Fourth Design #ssue

Last 3 design iss1es co,bine to provide protected


variations *ro, the var.ing inter*aces o* e5terna%
services

Ge5t design prob%e, is to provide ,ore co,p%e5


pricing %ogicA e:g:A
)
0 storeCwide disco1nt *or the da.
)
Senior citiNen disco1nts

The pricing po%ic. *or a sa%e can var.


CSIT!"" 32 scc
Fourth Design #ssue

Ihat pattern's( ,ight he%p@


)
3raw a separate c%ass diagra, *or it
)
3raw a seB1ence diagra, to show how the
new c%asses work with the origina% c%asses
CSIT!"" 33 scc
Fourth Design #ssue -Ans.er/

The Strateg. pattern ,ight he%p


)
Since the behavior o* pricing varies b. the
strateg. 'a%gorith,(A we create ,1%tip%e
SalePricingStrategy c%asses
)
Jach strateg. c%ass has a po%.,orphic
getTotal ,ethod
CSIT!"" 3# scc
Fourth Design #ssue -Ans.er/

C%ass diagra,
77inter*ace88
Sa%e&ricingStrateg.

getTota%'Sa%e( : -one.
&ercent3isco1nt
&ricingStrateg.
percentage : *%oat
getTota%'s: Sa%e( : -one.
0bso%1te3isco1ntOverThresho%d
&ricingStrateg.
disco1nt : -one.
thresho%d : -one.
getTota%'s: Sa%e( : -one.
@@@
&ricingStrateg.
K
getTota%'s: Sa%e( : -one.
CSIT!"" 3 scc
Fourth Design #ssue -Ans.er/

SeB1ence diagra,
pdt := get&re3isco1ntTota%' (
s : Sa%e
t := getTota%' (
< : st := getS1btota%' (
t := getTota%' s (
:Sa%eLineIte,
:&ercent3isco1nt
&ricingStrateg.
Sa%e&ricingStrateg.
CSIT!"" 36 scc
Fifth Design #ssue

0nother interesting design prob%e,


)
?ow do we hand%e the case o* ,1%tip%eA
con*%icting pricing po%ices@
)
S1ppose the *o%%owing po%icies in e**ect

2"O senior disco1nt po%ic.

!O o** sa%es over P#"" *or pre*erred c1sto,er

On -onda.A P" o** p1rchases over P""

$1. ! case o* Eava co**eeA get !O disco1nt o*


ever.thing
CSIT!"" 32 scc
Fifth Design #ssue
)
S1ppose a c1sto,er

Is a senior

Is a%so a pre*erred c1sto,er

&1rchases on -onda.

$1. ! case o* Eava co**ee

$1. P6"" o* tea


)
Ihat pricing po%ic. sho1%d be app%ied@
)
D$est *or the c1sto,erF '%owest price(
con*%ict reso%1tion strateg. is co,,on
CSIT!"" 3> scc
Fifth Design #ssue
)
$1t what i* we want that it co1%d be
changed@ J:g:A can switch to Dhighest
priceF reso%1tion d1ring a di**ic1%t *inancia%
period
)
Ie need a design that the Sa%e object
does not know i* it is dea%ing with one or
,an. pricing strategies

Ihat pattern's( ,ight he%p@


)
&%ease draw a separate c%ass diagra, *or it
CSIT!"" 3L scc
Fifth Design #ssue -Ans.er/

The Co,posite pattern ,ight he%p


77inter*ace88
Sa%e&ricingStrateg.

getTota%'Sa%e( : -one.
&ercent3isco1nt
&ricingStrateg.
percentage : *%oat
getTota%'s: Sa%e( : -one.
0bso%1te3isco1ntOverThresho%d
&ricingStrateg.
disco1nt : -one.
thresho%d : -one.
getTota%'s: Sa%e( : -one.
Composite
PricingStrategy
add'Sa%e&ricingStrateg.(
getTotal(s: Sale) : Money
Sa%e
date
K
getTota%' (
Co,posite$estForC1sto,er
&ricingStrateg.
getTota%'s: Sa%e( : -one.
Co,posite$estForStore
&ricingStrateg.
getTota%'s: Sa%e( : -one.
pricingStrateg. pricingStrateg.
!::< !
<
<
CSIT!"" #" scc
Fifth Design #ssue -Ans.er/

Co%%aboration with a Co,posite


< : 5 := getTota%'s(
s : Sa%e
t := getTota%' (
< : st := getS1btota%' (
t := getTota%' s (
:Sa%eLineIte,
:Co,posite$estForC1sto,er
&ricingStrateg.
Sa%e&ricingStrateg.
:Object
Sa%e&ricingStrateg.
CSIT!"" #! scc
References

J: Ga,,aA et a%:A 3esign &atterns:


J%e,ents o* +e1sab%e ObjectCOriented
So*twareA 0ddisonCIes%e. !LL:

Jric Free,an Q J%isabeth Free,anA ?ead


First 3esign &atternsA 2""#:

$: -e.erA 0pp%.ing 3esign b. ContractA


IJJJ Co,p1terA 2 '!"(A !LL2:

-: Fow%erA 0na%.sis &atterns: +e1sab%e


Object -ode%sA 0ddisonCIes%e.A !LL2
CSIT!"" #2 scc
On!ine Resources

http:HHhi%%side:netHpatternsH

http:HHc2:co,HpprH

http:HHso1rce,aking:co,HdesignRpatterns

http:HHwww:javaca,p:orgHdesign&atternH
Architecture Meeting Challenges
Via Discipline
CSIT5100
CSIT5100
S.C. Cheung
May 2014
CSIT5100 2 S.C. Cheung
Software Architecture
Architectural
Centric
Scalability
Reliability
Maintainability
Extensibility
Sot!are "uality Issues
Sot!are #rocess
CSIT5100 $ S.C. Cheung
Architectural Centric
Architectural
Centric
Scalability
Reliability
Maintainability
Extensibility
"uality issues arise% because
o co&'lexity
CSIT5100 4 S.C. Cheung
Trends in Software Technology
Manage Cople!ity
Manage Cople!ity
"ia "ia
Additional Discipline
Additional Discipline
Discipline in requirement modeling
Discipline in design
Discipline in programming
Discipline in testing
Discipline in requirement modeling
Discipline in design
Discipline in programming
Discipline in testing
Architecture
CSIT5100 ( S.C. Cheung
#ntity $ife%Cycles

Entity )ie*cycles are essentially state %iagra&s


o classes. +They %escribe the states entities
e,ol,e ro& creation to co&'letion.-

.arious +generic- &o%els o entity lie*cycle &ay


be su''orte%.
/
Entity )ie*Cycles or Running 0istory Entities
/
Entity )ie*Cycles or Mo%iiable Entities
/
Entity )ie*Cycles or Mo%iiable 1 2eletable Entities
CSIT5100 3 S.C. Cheung
&unning 'istory #ntities

Exa&'le

Interest rate on 204A'r41556 is %eter&ine by Ro! $.

Ro!s &ay ha,e i%entical eecti,e ti&e4%ate *7 resol,e by the latest


.eriie% 2ate.

Su''ort Create8 9'%ate8 Cancellation 1 .eriication.

:nce an entity +or ro!- is ,eriie%8 it &ay not be u'%ate% any&ore.

;eore an entity +or ro!- is ,eriie%8 it &ay be u'%ate%.

To &o%iy the <0istory=8 ne! entity +or ro!- shoul% be a%%e%.


Row Interest Rate Effective Date Verified Date
1 4.00% 01/Mar/1 01/Mar/1
! 4.!"% 0!/Mar/1 0!/Mar/1
# 4.$"% 1"/%&r/1 1"/%&r/1
4 ".00% 1!/Ma'/1 1!/Ma'/1
" "."0% 1#/(un/1 1#/(un/1

CSIT5100 6 S.C. Cheung
#"ents in the $ife%Cycle

Creation
/ An entity >ust create% !ill be 'lace% in an un,eriie% state. The na&e o the
creator an% a ti&e*sta&' !ill be hel% as 'art o the create re?uest.

9'%ate
/ @hen an u'%ate re?uest is &a%e against an un,eriie% entity8 the u'%ate
re?uest is a%%e% an% &arAe%. A%%itional u'%ate can be entere%.

Cancellation
/ The latest change re?uest can be cancelle% by the originator8 'ro,i%ing no
a%%itional re?uests ha,e been entere% against it an% it has not been ,eriie%
or re>ecte% in the &eanti&e.

.eriication
/ Acce't or re>ect on the latest ,ersion o the entity.
CSIT5100 5 S.C. Cheung
#ntity $ife%Cycle for &unning
'istory #ntities
,eriie%
u'%ateRe?uest
createRe?uest
,eriie%
u'%ateRe?uest
createRe?uest
create
u'%ate un%o
,eriy
u'%ate un%o
un%o re>ect
re>ect
non*existent
non*existent
,eriy
CSIT5100 10 S.C. Cheung
Modi(a)le #ntities

Conce't o a Master Co'y instea% o a Running 0istory

Master Co'y u'%ate% only i u'%ates are ,eriie%.

;eore .eriie%8 Master Co'y is use% by syste& an% inter&e%iate


changes are recor%e%.

.eriication incor'orates u'%ates to Master Co'y.


/ A conce't o Ex'iry

Re>ection %iscar%s all inter&e%iate changes.

Thus8 unliAe the Running 0istory Entities8 ,eriie% entities are


allo!e% to be u'%ate%.

Si&'le extension to 're,ious lie*cycle.


CSIT5100 11 S.C. Cheung
$ife%Cycle for Modi(a)le
#ntities
createRe?uest
,eriie%
u'%ateRe?uest
u'%ateRe?uestAter.eriie%
un%o
create
un%o re>ect
,eriy
u'%ate
u'%ate un%o
re>ect
u'%ate
un%o
,eriy
u'%ate
re>ect
un%o
non*existent
non*existent
,eriy
CSIT5100 12 S.C. Cheung
Modi(a)le * Deleta)le #ntities

Master co'y &ay be %elete% as !ell as u'%ate%

As in Mo%iiable Entities8 2elete Re?uests %o not taAe eect until it is


,eriie%.

:utstan%ing 2elete Re?uest &ay be ,eriie% or re>ecte% or cancelle%.

.eriie% 2elete are inal.

2elete Re?uests %o not a''ly to Entities that ha% not been ,eriie% at
least once beore.

Exa&'les8
/ #ublic 0oli%ay Entities
/ Associations bet!een Currencies*#olitical Entities8 0oli%ays*#olitical
Entities8 an% #olitical Entities*#olitical Entities.
CSIT5100 1$ S.C. Cheung
$ife%Cycle for Modi(a)le *
Deleta)le #ntities
createRe?uest
,eriie%
u'%ateRe?uest
u'%ateRe?uestAter.eriie%
%eleteRe?uest
%elete.eriie%
un%o
create
un%o re>ect
,eriy
u'%ate
,eriy
re>ect
un%o
u'%ate
u'%ate un%o
re>ect
u'%ate un%o
,eriy
re&o,e
un%o
re>ect
non*existent
non*existent
,eriy
CSIT5100 14 S.C. Cheung
ti&eSta&' B int
state B int
get)CManager+-
set)CManager+-
getTi&eSta&'+-
incrTi&eSta&'+-
setState+-
getState+-
is2irty+-
2ataIte&
create+-
u'%ate+-
re&o,e+-
cancel+-
re>ect+-
,eriy+-
)CMgrIc
CCInterace77
i% B String
create+-
store+-
loa%+-
re&o,e+-
setI2+-
getI2+-
#ersistenceEntity
ac?uire+-
release+-
#oolMgr
o'en+-
close+-
begin+-
co&&it+-
abort+-
execute"uery+-
execute9'%ate+-
Connection
isIn+-
getIte&+-
a%%Ite&+-
re&o,eIte&+-
2ataCollection
o'en+-
close+-
ac?uire+-
release+-
#oolIc
CCInterace77
)CMgr
occu'ie%
1
D
1
D
a,ailable
1
D
i&'le&ent
1
i&'le&ent
2ataIte&
)CMgrIc
#ersistenceEntity
#oolMgr
Connection
2ataCollection
ti&eSta&' B int
state B int
get)CManager+-
set)CManager+-
getTi&eSta&'+-
incrTi&eSta&'+-
setState+-
getState+-
is2irty+-
i% B String
create+-
store+-
loa%+-
re&o,e+-
setI2+-
getI2+-
ac?uire+-
release+-
o'en+-
close+-
begin+-
co&&it+-
abort+-
execute"uery+-
execute9'%ate+-
isIn+-
getIte&+-
a%%Ite&+-
re&o,eIte&+-
create+-
u'%ate+-
re&o,e+-
cancel+-
re>ect+-
,eriy+-
o'en+-
close+-
ac?uire+-
release+-
#oolIc
)CMgr
CSIT5100 15 S.C. Cheung
2ataIte&
rate B int
%ate B int
setRate+-
getRate+-
set2ate+-
get2ate+-
Interest
CSIT5100 1( S.C. Cheung
Iportance of Software
Architecture

As a coherent solution
/ #ositi,e eects on %e,elo'er &orale an% 'ro%ucti,ity

Allo! the solution to be re,ie!e% beore i&'le&ente%


/ Mini&iEe conusion an% risA

;lue'rint i&'ro,es coor%ination


/ Facilitates a &ore or%erly %e,elo'&ent 'rocess8 inclu%ing 'lanning
o a testing be%
CSIT5100 13 S.C. Cheung
Iportance of Software
Architecture

@hat i a sot!are architecture is &issingGH


/ 2e,elo'ers unsure ho! their eorts contribute to the !hole syste&
/ Crisis o inco&'atible integration
CSIT5100 16 S.C. Cheung
This is the end of course )ut
your learning will surely continue+

You might also like