Object Oriented Analysis Lecture 5 1© Clear View Training 2010 v2.6 Outline  Objects and classes [Lecture 4]  Finding analysis classes [Lecture 4]  Relationships between objects and classes  Links  Associations  Dependencies  Inheritance and polymorphism  Interaction diagrams 2© Clear View Training 2010 v2.6 Relationships Between Objects and Classes Lecture 5/Part 1 3© Clear View Training 2010 v2.6 © Clear View Training 2010 v2.6 4 What is a relationship?  A relationship is a connection between modelling elements  In this section we’ll look at:  Links between objects  Associations between classes • aggregation • composition • association classes  Dependencies between model elements © Clear View Training 2010 v2.6 5 What is a link?  Links are connections between objects  Think of a link as a telephone line connecting you and a friend. You can send messages back and forth using this link  Links are the way that objects communicate  Objects send messages to each other via links  Messages invoke operations  OO programming languages implement links as object references or pointers. These are unique handles that refer to specific objects  When an object has a reference to another object, we say that there is a link between the objects © Clear View Training 2010 v2.6 6 Object diagrams  Paths in UML diagrams (lines to you and me!) can be drawn as orthogonal, oblique or curved lines  We can combine paths into a tree if each path has the same properties bookClub:Club ila:Person erica:Person naomi:Person chairperson secretary member role name link BookClub bookClub:Club ila:Person erica:Person naomi:Person chairperson secretary member BookClub oblique path style orthogonal path style preferred object © Clear View Training 2010 v2.6 7 What is an association?  Associations are relationships between classes  Associations between classes indicate that there are links between objects of those classes  A link is an instantiation of an association just as an object is an instantiation of a class bookClub:Club jim:Person chairman Club Person «instantiate» «instantiate» «instantiate» link association links instantiate associations © Clear View Training 2010 v2.6 8 Association syntax  An association can have role names or an association name  It’s bad style to have both!  The black triangle indicates the direction in which the association name is read:  “A Company employs many Persons” Company Person 1 * employs navigability association name multiplicity Company Person employer employee 1 * role names © Clear View Training 2010 v2.6 9 Multiplicity  Multiplicity is a constraint that specifies the number of objects that can participate in a relationship at any point in time  If multiplicity is not explicitly stated in the model then it is undecided – there is no default multiplicity Company Person employee 1 * employer A Company employs many People Each Person works for one Company multiplicity syntax: minimum..maximum 0..1 zero or 1 1 exactly 1 0..* zero or more * zero or more 1..* 1 or more 1..6 1 to 6 © Clear View Training 2010 v2.6 10 Multiplicity exercise  How many  Employees can a Company have?  Employers can a Person have?  Owners can a BankAccount have?  Operators can a BankAccount have?  BankAccounts can a Person have?  BankAccounts can a Person operate? Company Person employee 1 7 employer BankAccount 0..* 1owner 0..* 1..* operator © Clear View Training 2010 v2.6 11 Reflexive associations: file system example Directory File 0..*10..* 0..1 C Windows My Documents Corel Command autoexec config To John directories files parent subdirectory reflexive association © Clear View Training 2010 v2.6 12 Hierarchies and networks A 0..* 0..1 a1:A b1:A c1:A d1:A e1:A f1:A g1:A B 0..* 0..* a1:B b1:B c1:B d1:Be1:B f1:B g1:B hierarchy network an an association hierarchy, each object has zero or one object directly above it in an association network, each object has zero or many objects directly above it © Clear View Training 2010 v2.6 13 Navigability  Navigability indicates that it is possible to traverse from an object of the source class to objects of the target class  Objects of the source class may reference objects of the target class using the role name  Even if there is no navigability it might still be possible to traverse the relationship via some indirect means. However the computational cost of the traversal might be very high Order Product* * Not navigable A Product object does not store a list of Orders An Order object stores a list of Products Navigable source target navigability A B A B A B A B A to B is navigable B to A is navigable A to B is navigable B to A is not navigable A to B is navigable B to A is undefined A to B is undefined B to A is undefined © Clear View Training 2010 v2.6 14  Strict UML2 navigability can clutter diagrams so the UML standard suggests three possible modeling idioms: 1. Show navigability explicitly on diagrams with crosses and arrows 2. Omit all navigability from diagrams 3. Omit crosses from diagrams • bi-directional associations have no arrows • unidirectional associations have a single arrow • you can't show associations that are not navigable in either direction (not useful anyway!) A B A B A to B is navigable B to A is not navigable A to B is navigable B to A is navigable standard practice Navigability – standard practice © Clear View Training 2010 v2.6 15 Associations and attributes  If a navigable relationship has a role name, it is as though the source class has a pseudoattribute whose attribute name is the role name and whose attribute type is the target class  Objects of the source class can refer to objects of the target class using this pseudo-attribute  Use associations when:  The targetclass is an importantpart of the model  The targetclass is a class thatyou have designed yourselfand which mustbe shown on the model  Use attributes when:  The targetclass is not an importantpart of the modele.g. a primitive type such as number,string etc.  The targetclass is just an implementationdetailsuch as a bought-in componentora library componente.g.Java.util.Vector(from the Java standard libraries) address:Address House House Address 1 1 address House address:Address pseudo-attribute attribute = © Clear View Training 2010 v2.6 16 Association classes  Not on the Person class - there is a different salary for each employment  Not on the Company class - different Person objects have different salaries  The salary is a property of the employment relationship itself  every time a Person object is employed by a Company object, there is a salary Company Person * * Each Person object can work for many Company objects. Each Company object can employ many Person objects. When a Person object is employed by a Company object, the Person has a salary. But where do we record the Person’s salary? employment © Clear View Training 2010 v2.6 17 Association class syntax  We model the association itself as an association class. One instance of this class exists for each link between a Person object and a Company object  Instances of the association class are links that have attributes and operations  Can only use association classes when there is one unique link between two specific objects. This is because the identity of links is determined exclusively by the identities of the objects on the ends of the link  We can place the salary and any other attributes or operations which are really features of the association into this class Company Person* * Job salary:double the association class consists of the class, the association and the dashed line association class © Clear View Training 2010 v2.6 18 Using association classes Company Person* * Job salary:double If we use an association class, then a particular Person can have only one Job with a particular Company If, however a particular Person can have multiple jobs with the same Company, then we must use a reified association Company Person Job salary:double ** 11 © Clear View Training 2010 v2.6 19 Qualifiedassociations  Qualified associations reduce an n to many association to an n to 1 association by specifying a unique object (or group of objects) from the set  They are useful to show how we can look up or navigate to specific objects  Qualifiers usually refer to an attribute on the target class Club Member 1 * Club Member 1 0..1 memberId memberId:String memberId:String the combination (Club, memberId) specifies a unique target object qualifier © Clear View Training 2010 v2.6 20 Dependencies  "Adependency is a relationship between two elements where a change to one element (the supplier) may affect or supply information needed by the other element (the client)". In other words, the client depends in some way on the supplier  Dependency is really a catch-all that is used to model several different types of relationship. We’ve already seen one type of dependency, the «instantiate» relationship  Three types of dependency:  Usage - the client uses some of the services made available by the supplier to implement its own behavior – this is the most commonly used type of dependency  Abstraction - a shift in the level of abstraction. The supplier is more abstract than the client  Permission - the supplier grants some sort of permission for the client to access its contents – this is a way for the supplier to control and limit access to its contents © Clear View Training 2010 v2.6 21 Usage dependencies  «use» - the client makes use of the supplier to implement its behaviour  «call» - the client operation invokes the supplier operation  «parameter» - the supplier is a parameter of the client operation  «send» - the client (an operation) sends the supplier (a signal) to some unspecified target  «instantiate» - the client is an instance of the supplier © Clear View Training 2010 v2.6 22 «use» - example A foo( b : B ) bar() : B doSomething() B A :: doSomething() { B myB = new B(); … } «use» A «use» dependency is generated between class Aand B when: 1) An operation of class A needs a parameter of class B 2) An operation of class A returns a value of class B 3) An operation of class A uses an object of class B somewhere in its implementation the stereotype is often omitted © Clear View Training 2010 v2.6 23 Abstraction dependencies  «trace» - the client and the supplier represent the same concept but at different points in development  «substitute» - the client may be substituted for the supplier at runtime. The client and supplier must realize a common contract. Use in environments that don't support specialization/generalization  «refine» - the client represents a fuller specification of the supplier  «derive» - the client may be derived from the supplier. The client is logically redundant, but may appear for implementation reasons © Clear View Training 2010 v2.6 24 «derive» - example BankAccount Transaction 1 0..* Quantity 1 1 1balance «derive» BankAccount Transaction 1 0..* Quantity 1 1 1/balance BankAccount Transaction 1 0..* /balance:Quantity Quantity 1 1 This example shows three possible ways to express a «derive» dependency © Clear View Training 2010 v2.6 25 Permission dependencies «access»  The public contents of the supplier package are added as private elements to the namespace of the client package «import»  The public contents of the supplier package are added as public elements to the namespace of the client package «permit»  The client element has access to the supplier element despite the declared visibility of the supplier © Clear View Training 2010 v2.6 26 Key points  Links – relationships between objects  Associations – relationships between classes  role names  multiplicity  navigability  associationclasses  qualified associations  Dependencies – relationships between model elements  usage  abstraction  permission © Clear View Training 2010 v2.6 27 Inheritance and polymorphism Lecture 5/Part 2 © Clear View Training 2010 v2.6 28 Generalisation  A relationship between a more general element and a more specific element  The more specific element is entirely consistent with the more general element but contains more information  An instance of the more specific element may be used where an instance of the more general element is expected Substitutability Principle © Clear View Training 2010 v2.6 29 Example: class generalisation Shape Square Circle Triangle more general element more specific elements parent superclass base class ancestor child subclass descendent generalisation specialisation A generalisation hierarchy “is kind of” © Clear View Training 2010 v2.6 30 Class inheritance  Subclasses inherit all features of their superclasses:  attributes  operations  relationships  stereotypes, tags, constraints  Subclasses can add new features  Subclasses can override superclass operations  We can use a subclass instance anywhere a superclass instance is expected Substitutability Principle Shape origin : Point = (0,0) width : int {>0} height: int {>0} draw(g : Graphics ) getArea(): int getBoundingArea(): int Square Circle radius : int = width/2 {width = height} Butwhat’s wrong with these subclasses © Clear View Training 2010 v2.6 31 Overriding  Subclasses often need to override superclass behaviour  To override a superclass operation, a subclass must provide an operation with the same signature  The operation signature is the operation name, return type and types of all the parameters  The names of the parameters don’t count as part of the signature Shape draw(g : Graphics ) getArea(): int getBoundingArea(): int Square Circle draw(g : Graphics ) getArea(): int draw(g : Graphics ) getArea(): intwidth x height p x radius2 © Clear View Training 2010 v2.6 32 Abstract operations & classes  We can’t provide an implementation for Shape :: draw( g : Graphics ) or for Shape :: getArea() : int because we don’t know how to draw or calculate the area for a "shape"!  Operations that lack an implementation are abstract operations  A class with any abstract operations can’t be instantiated and is therefore an abstract class concrete operations Shape draw(g : Graphics ) getArea(): int getBoundingArea(): int Square Circle draw(g : Graphics ) getArea(): int draw(g : Graphics ) getArea(): int abstractclass concrete classes abstract operations abstract class and operation names must be in italics © Clear View Training 2010 v2.6 33 Exercise Vehicle JaguarXJS Truck what’s wrong with this model? © Clear View Training 2010 v2.6 34 Polymorphism  Polymorphism = "many forms"  A polymorphic operation has many implementations  Square and Circle provide implementations for the polymorphic operations Shape::draw() and Shape::getArea()  All concrete subclasses of Shape must provide concrete draw() and getArea() operations because they are abstract in the superclass  For draw() and getArea() we can treat all subclasses of Shape in a similar way - we have defined a contract for Shape subclasses Shape draw( g : Graphics ) getArea() : int getBoundingArea() : int Square Circle draw( g : Graphics ) getArea() : int draw( g : Graphics ) getArea() : int polymorphic operations concrete subclasses abstract superclass Canvas * 1 A Canvas object has a collection of Shape objects where each Shape may be a Square or a Circle shapes © Clear View Training 2010 v2.6 35 What happens?  Each class of object has its own implementation of the draw() operation  On receipt of the draw() message, each object invokes the draw() operation specified by its class  We can say that each object "decides" how to interpret the draw() message based on its class :Canvas s1:Circle s2:Square s3:Circle s4:Circle 1.draw() 2.draw() 3.draw() 4.draw() © Clear View Training 2010 v2.6 36 BankAccount example  We have overridden the deposit() operation even though it is not abstract. This is perfectly legal, and quite common, although it is generally considered to be bad style and should be avoided if possible BankAccount withdraw() calculateInterest() deposit() CheckingAccount DepositAccount withdraw() calculateInterest() withdraw() calculateInterest() Bank *1 ShareAccount withdraw() calculateInterest() deposit() © Clear View Training 2010 v2.6 37 Key points  Subclasses:  inherit all features from their parents including constraints and relationships  may add new features, constraints and relationships  may override superclass operations  A class that can’t be instantiated is an abstract class © Clear View Training 2010 v2.6 38 Lecture 5/Part 3 Interaction Diagrams © Clear View Training 2010 v2.6 39 Use Case realization  Use case realizations consist of the following elements:  Analysis class diagrams • These show relationships between the analysis classes that interact to realise the UC  Interaction diagrams • These show collaborations between specific objects that realise the UC. They are “snapshots” of the running system  Special requirements • UC realization may well uncover new requirements specific to the use case. These must be captured  Use case refinement • We may discover new information during realization that means that we have to update the original UC © Clear View Training 2010 v2.6 40 Interactions  Interactions are units of behavior of a context classifier  In use case realization, the context classifier is a use case  The interaction shows how the behavior specified by the use case is realized by instances of classifiers  Interaction diagrams capture an interaction as:  Lifelines – participants in the interaction  Messages – communications between lifelines © Clear View Training 2010 v2.6 41 Lifelines  A lifeline represents a single participant in an interaction  Shows how a classifier instance may participate in the interaction  Lifelines have:  name - the name used to refer to the lifeline in the interaction  selector - a boolean condition that selects a specific instance  type - the classifier that the lifeline represents an instance of  They must be uniquely identifiable within an interaction by name, type or both  The lifeline has the same icon as the classifier that it represents  The lifeline jimsAccount represents an instance of the Account class  The selector [ id = "1234" ] selects a specific Account instance with the id "1234" jimsAccount [ id = "1234" ] : Account name selector type © Clear View Training 2010 v2.6 42 Messages  A message represents a communication between two lifelines synchronous message asynchronous send message return sender receiver/ target creation:A type of message destruction found message lost message calling an operation synchronously the senderwaits forthe receiverto complete calling an operation asynchronously,sendinga signal the senderdoes notwait for the receiverto complete semantics returning from a synchronous operation call the receiverreturns focus of controlto the sender the sendercreates the target the senderdestroysthe receiver the message is sentfrom outside the scope of the interaction the message fails to reach its destination © Clear View Training 2010 v2.6 43 Interaction diagrams  Sequence diagrams  Emphasize time-ordered sequence of message sends  Show interactions arranged in a time sequence  Are the richest and most expressive interaction diagram  Do not show object relationships explicitly - these can be inferred from message sends  Communication diagrams  Emphasize the structural relationships between lifelines  Use communication diagrams to make object relationships explicit  Interaction overview diagrams  Show how complex behavior is realized by a set of simpler interactions (discussed earlier together with Activity diagrams)  Timing diagrams  Emphasize the real-time aspects of an interaction © Clear View Training 2010 v2.6 44 Sequence diagram syntax  All interaction diagrams may be prefixed sd to indicate their type  You can generally inferdiagram types from diagramsyntax  Activations indicate when a lifeline has focus of control - they are often omitted from sequence diagrams :Registrar :RegistrationManager uml:Course addCourse("UML" ) «create» notes can form a "script" describing the flow lifeline sd AddCourse objectcreation message synchronous message objectis created at this point message return activation The Registrar selects "add course". The system creates the new Course. © Clear View Training 2010 v2.6 45 Deletion and self-delegation  Self delegation is when a lifeline sends a message to itself  Generates a nested activation  Object deletion is shown by terminating the lifeline's tail at the point of deletion by a large X :Registrar :RegistrationManager uml:Course deleteCourse("UML" ) sd DeleteCourse objectis deleted at this point «destroy» self delegation findCourse("UML" ) nested activation © Clear View Training 2010 v2.6 46 State invariants and constraints :Customer :Order :DeliveryManager:OrderManager «create» unpaid paid delivered raiseOrder() acceptPayment() acceptPayment() deliver() deliver() state invariant A B {B – A <= 28 days} label sd ProcessAnOrder constraint © Clear View Training 2010 v2.6 47 Combined fragments  Sequence diagrams may be divided into areas called combined fragments  Combined fragments have one or more operands  Operators determine how the operands are executed  Guard conditions determine whether operands execute. Execution occurs if the guard condition evaluates to true  A single condition may apply to all operands OR  Each operand may be protected by its own condition name op [guard condition 2] b( ) c( ) guard conditions mustbe placed above the first eventoccurrence :A :B :C operator operands a( ) combined fragment [guard condition 1] © Clear View Training 2010 v2.6 48 operator long name semantics opt Option There is a single operand that executes if the condition is true (like if … then) alt Alternatives The operand whose condition is true is executed. The keyword else may be used in place of a Boolean expression (like select… case) loop Loop This has a special syntax: loop min, max [condition] Iterate min times and then up to max times while condition is true break Break The combined fragment is executed rather than the rest of the enclosing interaction ref Reference The combined fragment refers to another interaction findStudent(name):Student ref ref has a single operand that is a reference to another interaction. This is an interaction use. Common operators © Clear View Training 2010 v2.6 49 The rest of the operators  These operators are less common operator long name semantics par parallel Both operands execute in parallel seq weak sequencing The operands execute in parallel subject to the constraint that event occurrences on the same lifeline from different operands must happen in the same sequence as the operands strict strict sequencing The operands execute in strict sequence neg negative The combined fragment represents interactions that are invalid critical critical region The interaction must execute atomically without interruption ignore ignore Specifies that some messages are intentionally ignored in the interaction consider consider Lists the messages that are considered in the interaction (all others are ignored) assert assertion The operands of the combined fragments are the only valid continuations of the interaction © Clear View Training 2010 v2.6 50 Branching with opt and alt  opt semantics:  single operand that executes if the condition is true  alt semantics:  two or more operands each protected by its own condition  an operand executes if its condition is true  use else to indicate the operand that executes if none of the conditions are true :A :B :C :D opt [condition] do this if condition is true alt do this if condition1 is true [condition1] [condition2] do this if condition2 is true [else] do this if neither condition is true sd example of opt and alt © Clear View Training 2010 v2.6 51 Iteration with loop and break  loop semantics:  Loop min times, then loop (max – min) times while condition is true  loop syntax  A loop without min, max or condition is an infinite loop  If only min is specified then max = min  condition can be • Booleanexpression • Plain text expression providedit is clear!  Break specifies what happens when the loop is broken out of:  The break fragment executes  The rest of the loop after the break does not execute  The break fragment is outside the loop and so should overlap it as shown :A :B loop min, max [condition] do something sd examples of loop loop [condition] do something loop while guard condition is true break on breaking out do this do something else must be global relative to loop © Clear View Training 2010 v2.6 52 Loop idioms type of loop semantics loop expression infinite loop keep looping forever loop * for i = 1 to n {body} repeat ( n ) times loop n while( booleanExpression ) {body} repeat while booleanExpression is true loop [ booleanExpression ] repeat {body} while( booleanExpression ) execute once then repeat while booleanExpression is true loop 1, * [booleanExpression] forEach object in collection {body} Execute the loop once for each object in a collection loop [for each object in collection] forEach object in ObjectType {body} Execute the loop once for each object of a particular type loop [for each object in :ObjectType] © Clear View Training 2010 v2.6 53 addCourse( "UML" ) uml = Course("UML") addCourse( "UML" ) Sequence diagrams in design :Registrar :RegistrationUI uml:Course sd AddCourse-design :RegistrationManager :DBManager save(uml) © Clear View Training 2010 v2.6 54  Communication diagrams emphasize the structural aspects of an interaction - how lifelines connect together  Compared to sequence diagrams they are semantically weak  Object diagrams are a special case of communication diagrams 2: addCourse("MDA" ) :Registrar :RegistrationManager mda:Course uml:Course 1: addCourse("UML" ) 1.1:«create» 2.1:«create» sd AddCourses link messagesequence number lifeline objectcreation message Communication diagram syntax © Clear View Training 2010 v2.6 55 Iteration  Iteration is shown by using the iteration specifier (*), and an optional iteration clause  There is no prescribed UML syntax for iteration clauses  Use code or pseudo code  To show that messages are sent in parallel use the parallel iteration specifier, *// iteration clause 1: printCourses() :Registrar :RegistrationManager [i]:Course 1.1.1:print() 1.1 * [for i = 1 to n] : printCourse(i ) sd PrintCourses iteration specifier © Clear View Training 2010 v2.6 56 Branching  Branching is modelled by prefixing the sequence number with a guard condition  There is no prescribed UML syntax for guard conditions!  In the example above, we use the variable found. This is true if both the student and the course are found, otherwise it is false :RegistrationManager 1: register( "Jim", "UML" ) :Registrar course:Course 1.3 [found]: register( student) 1.1:student= findStudent("Jim" ) 1.4 [!found]: error() 1.2:course = findCourse("UML" ) sd registerstudentforcourse It’s hard to show branching clearly!! found = (student!= null) & (course != null) guard condition return value from message © Clear View Training 2010 v2.6 57 {t <= 15} {t = 10}{t > 30} {t <= 15} {t = 30} Timing diagrams  Emphasize the real-time aspects of an interaction  Used to model timing constraints  Lifelines, their states or conditions are drawn vertically, time horizontally  It's important to state the time units you use in the timing diagram sd IntruderThenFire soundingFireAlarm soundingIntruderAlarm off :Siren 0 10 20 30 40 50 state or condition lifeline intruder intruder fire time in minutes event timing ruler duration constraint 60 resting 70 80 90 100 sd IntruderThenFire sounding Intruder Alarm :Siren off resting sounding Intruder Alarm sounding fire Alarm state or condition all times in minutes compact form © Clear View Training 2010 v2.6 58 {t <= 0.016} {t <= 0.016} soundIntruderAlarm() soundIntruderAlarm() soundIntruderAlarm() soundIntruderAlarm() soundFireAlarm() Messages on timing diagrams  You can show messages between lifelines on timing diagrams  Each lifeline has its own partition sd SirenBehavior soundingIntruderAlarm off :Siren {t <= 15} triggered notTriggered :IntruderSensorMonitor {t <= 15}{t = 30} all times in minutes resting triggered notTriggered :FireSensorMonit or soundingFireAlarm messages © Clear View Training 2010 v2.6 59 Key points  In this section we have looked at use case realization using interaction diagrams  There are four types of interaction diagram:  Sequence diagrams – emphasize time-ordered sequence of message sends  Communication diagrams – emphasize the structural relationships between lifelines  Interaction overview diagrams – show how complex behavior is realized by a set of simpler interactions; presented together with Activity diagrams  Timing diagrams – emphasize the real-time aspects of an interaction