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  State diagram 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 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  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 5 Object diagrams  Paths in UML diagrams 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 Shape Square Circle Triangle © Clear View Training 2010 v2.6 6 What is an association?  Associations are relationships between classes  Associations between classes indicate that there may be links between objects of those classes, while links indicates that there must be associations  Can there be a communication between objects of two classes that have no association between them? bookClub:Club jim:Person chairman Club Person «instantiate» «instantiate» «instantiate» link association links instantiate associations © Clear View Training 2010 v2.6 7 Association syntax  An association can have role names or an associationname  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 1 0..* employs navigability association name multiplicity Company Person employer employee 1 0..* role names multiplicity: min..max 0..1 zero or 1 1 exactly 1 0..* zero or more 1..* 1 or more 1..6 1 to 6 reading direction © Clear View Training 2010 v2.6 8 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 9 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 10 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 In 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 11 Navigability  Navigability indicates that it is possible to traverse from an object of the source class to objects of the target class  Can there be a communication in a direction not supported by the navigability?  Are some of the cases on the right equivalent? Order Product 0..* 0..* 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 12 Associations and attributes  An association is (through its role name) a representation of an attribute  Use associations when:  The target class is an important part of the model  The target class is a class that you have designed yourself  Use attributes when:  The target class is not important, e.g. a primitive type such as number, string  The target class is just an implementation detail such as a bought-in component or a library component e.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 13 Association classes Company Person 0..* 0..*employment  Where do we record the Person’s salary?  We model the association itself as an association class. Exactly one instance of this class exists for each link between a Person and a Company.  We can place the salary and any other attributes or operations which are really features of the association into this class Company Person 0..* 0..* Job salary:double the association class consists of the class, the association and the dashed line association class © Clear View Training 2010 v2.6 14 Using association classes Company Person 0..* 0..* 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 0..*0..* 11 © Clear View Training 2010 v2.6 15 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  Weaker type of relationship than association  Can there be both association and dependency between two classes?  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 16 Usage dependencies  Stereotypes  «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 A foo( b : B ) bar() : B doSomething() B A :: doSomething() { B myB = new B(); } «use» A «use» dependency is generated between A and B when B is used in A as a parameter, return value or inside method body the stereotype is often omitted © Clear View Training 2010 v2.6 17 Abstraction and permission dependencies  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  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 18 Key points  Links – relationships between objects  Associations – relationships between classes  role names  multiplicity  navigability  associationclasses  Dependencies – relationships between model elements  usage  abstraction  permission © Clear View Training 2010 v2.6 19 Inheritance and polymorphism Lecture 5/Part 2 © Clear View Training 2010 v2.6 20 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” A relationship between a more general element and a more specific element (with more information) © Clear View Training 2010 v2.6 21 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 What’s wrong with these subclasses? © Clear View Training 2010 v2.6 22 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 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 What’s wrong with the superclass? © Clear View Training 2010 v2.6 23 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 24 Exercise Vehicle JaguarXJS Truck what’s wrong with this model? © Clear View Training 2010 v2.6 25 Polymorphism  Polymorphism = "many forms"  A polymorphic operation has many implementations  Square and Circle provide implementations for the polymorphic operations Shape::draw() and Shape::getArea()  The operation in Shape superclass defines a contract for the 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 0..* 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 26 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 27 BankAccount example  We have overridden the deposit() operation even though it is not abstract. BankAccount withdraw() calculateInterest() deposit() CheckingAccount DepositAccount withdraw() calculateInterest() withdraw() calculateInterest() Bank 0..*1 ShareAccount withdraw() calculateInterest() deposit() © Clear View Training 2010 v2.6 28 Key points  Generalisation, specialisation, inheritance  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 29 UML State Diagram Lecture 7/Part 4 © Clear View Training 2010 v2.6 30 State machines  Models life stages of a single model element – e.g. object, use case, module  Every state machine exists in the context of a particular model element that:  Has a clear life history modelled as a progression of states, transitions and events  Responds to events dispatched from outside of the element  There are two types of state machines:  Behavioural state machines - define the behaviour of a model element  Protocol state machines - model the protocol of a classifier • E.g.call conditions and callordering of an interface thatitself has no behaviour Off On Off On turnOff burnOut light bulb turnOn © Clear View Training 2010 v2.6 31 Basic state machine syntax  State = a situation or condition during the life of an object  Determined at any point in time by the values of its attributes, the relationships to other objects, or the activities it is performing.  Every state machine should have one initial state which indicates the first state of the sequence  Unless the states cycle endlessly, state machines should have a final state which terminates its lifecycle A B anEvent initial state transition event state final state Color red : int green : int blue : int How many states? © Clear View Training 2010 v2.6 32 State syntax  Actions are instantaneous and uninterruptible  Entry actions occur immediately on state entry  Exit actions occur immediately on state leaving  Internal transitions occur within the state. They do not fire transition to a new state  Activities take a finite amount of time and are interruptible EnteringPassword entry/display passwd dialog exit/validate password keypress/ echo "*" help/display help do/get password entry and exit actions internal transitions internal activity Action syntax: eventTrigger / action Activity syntax: do / activity state name © Clear View Training 2010 v2.6 33 Transitions A B event1,event2 [guard condition]/ act1, act2 behavioralstate machine C D [precondition]event1,event2 /[postcondition] protocolstate machine{protocol} Protocol state machine Specifies legal sequences of events. Behavioral state machine Specifies object’s reactions to events. events guard condition actions precondition events postcondition © Clear View Training 2010 v2.6 34  Choice pseudo state directs its single incoming transition to one of its outgoing transitions  Each outgoing transition must have a mutually exclusive guard condition  Equivalent to two outgoing transitions from one state  Junction pseudo state connects multiple incoming transitions into one (or more) transitions.  When there are more outgoing transitions, they must have guard conditions Unpaid FullyPaid PartiallyPaidOverPaid [payment == balance] [payment > balance] [payment < balance] acceptPayment acceptPayment makeRefund BankLoan choice pseudo-state Choice and junction pseudo states junction pseudo state © Clear View Training 2010 v2.6 35 Events  "The specification of a noteworthy occurrence that has location in time and space"  Events trigger transitions in state machines  Events can be shown externally, on transitions, or internally within states (internal transitions)  There are four types of event:  Call event  Signal event  Change event  Time event Off On turnOff turnOn event © Clear View Training 2010 v2.6 36 close() Call event  A call for an operation execution  The event should have the same signature as an operation of the context class  A sequence of actions may be specified for a call event - they may use attributes and operations of the context class  The return value must match the return type of the operation InCredit deposit(m)/ balance = balance + m AcceptingWithdrawal entry/ balance = balance - m RejectingWithdrawal entry/ logRejectedWithdrawal() withdraw(m) [balance < m] withdraw(m) [balance >= m] internalcallevent action conditionexternalcallevent entry action SimpleBankAccount © Clear View Training 2010 v2.6 37 close() Signal events  A signal is a package of information that is sent asynchronously between objects InCredit deposit(m)/ balance = balance + m AcceptingWithdrawal entry/ balance = balance - m RejectingWithdrawal entry/ logRejectedWithdrawal() withdraw(m) [balance < m] withdraw(m) [balance >= m] SimpleBankAccount OverdrawnAccount send a signal «signal» OverdrawnAccount date : Date accountNumber : long amountOverdrawn:long Calling borrowerOverdrawnAccount signalreceipt © Clear View Training 2010 v2.6 38 close() Change events  The action is performed when the Boolean expression transitions from false to true  The event is edge triggered on a false to true transition  The values in the Boolean expression must be constants, globals or attributes of the context class  A change event implies continually testing the condition whilst in the state InCredit deposit(m)/ balance = balance + m balance >= 5000 / notifyManager() AcceptingWithdrawal entry/ balance = balance - m RejectingWithdrawal entry/ logRejectedWithdrawal() withdraw(m) [balance < m] withdraw(m) [balance >= m] SimpleBankAccount OverdrawnAccount Boolean expression © Clear View Training 2010 v2.6 39 Time events  Time events occur when a time expression becomes true  There are two keywords, after and when  Elapsed time:  after( 3 months )  Absolute time:  when( date =20/3/2000) Overdrawn balance < overdraftLimit / notifyManager Frozen after( 3 months ) Context: CreditAccount class © Clear View Training 2010 v2.6 40 Composite states  Have one or more regions that each contain a nested submachine  Simple composite state • exactly one region  Orthogonal composite state • two or more regions  The final state terminates its enclosing region – all other regions continue to execute  The terminate pseudo-state terminates the whole state machine A composite state A B C region 1 region 2 submachines Anothercomposite state D E F terminate pseudo-state © Clear View Training 2010 v2.6 41 [dialtone] after(20 seconds)/noDialtone after(20 seconds)/ noCarrier [carrier] cancel Simple composite states do/dialISP DialingISP entry/ offHook WaitingForDialtone Dialing WaitingForCarrier entry pseudo state notConnected dial connectedexitpseudo-state NotConnected Connected entry/onHook exit/onHook do/useConnection ISPDialer the nested states inheritthe canceltransition © Clear View Training 2010 v2.6 42 Orthogonal composite states  Has two or more regions  When we enter the superstate, both submachines start executing concurrently - this is an implicit fork do/ initializeSecuritySensor Initializing InitializingFireSensors do/ initializeFireSensor InitializingSecuritySensors Initializing composite state details do/ monitorSecuritySensor Monitoring MonitoringFireSensors do/ monitorFireSensor MonitoringSecuritySensors fire intruder Monitoring composite state details Synchronized exit - exit the superstate when both regions have terminated Unsynchronized exit - exit the superstate when either region terminates. The other region continues © Clear View Training 2010 v2.6 43 Key points  Behavioral and protocol state machines  States  Initial and final  Exit and entry actions, activities  Transitions  Guard conditions, actions  Events  Call, signal, change and time  Composite states  Simple and orthogonal composite states