CSC450 Software Engineering Devon M. Simmonds University of North Carolina, Wilmington Introduction to UML Class Diagrams Objectives Introduce basic class diagram constructs Introduce UML relationships Generalization Association Aggregation/composition Dependency Interfaces What is a class? A class is a description of a set of objects that share the same properties attributes Operations Java class public class Student { int id; Address addr; int graduate (String semester) } UML class Student Id:Integer addr:Address graduate(semester:String):int Structure of a class A class has the following structure: Name compartment (mandatory) Attributes compartment (optional) Operations compartment (optional) Every class must have a distinguishing name. An object is an instance of a class An object of a class must have values associated with each attribute of the class Name attributes operations Student Id:Integer Addr:String graduate(semester:String):int johnWayne:Student Id = 2007 Addr = “Wild Wild West” Class Notation name attributes operations Rectangle Rectangle height width attributes operations Rectangle getArea resize Rectangle height width getArea resize Attributes Window size:Area visibility:Boolean display() hide() An attribute is a named property. Each class instance associates value(s) with each attribute of a concept. What should be an attribute? Properties with types that we want to treat as primitive are modeled as attributes Connections to other classes are to be represented as associations, not attributes. Operations An operation is a procedure defined in a class. Each operation has a signature and a specification of its behavior. Signature: operation name, a list of argument types and the result type. operationName(parameterName: parameterType …): returnType Specification is expressed in terms of pre-and postconditions (the Object Constraint Language is used for this purpose) Operations II A method is the implementation of an operation. Classes in requirements and domain models DO NOT NEED to contain operations Rationale: in most cases, distributing operations across classes requires making design-level decision. Objectives Introduce basic class diagram constructs Introduce UML relationships Association Aggregation/composition Generalization Dependency UML Interfaces Modeling Static Class Relationships Association Aggregation/composition Generalization Dependency 10 Associations Associations represent conceptual relationships among problem concepts or classes. Association properties include Multiplicity Role Constraints Associations -"direction reading arrow" -it has no meaning except to indicate direction of reading the association label -often excluded Employee 1 works-for4 3 Company multiplicity Association name Multiplicity * Student zero or more; "many" Customer 1..* 1..40 Student one or more 0..1 Rents 6 Student one to forty * 5 3, 5, 8 Student exactly five Student exactly three, five or eight Video One instance of a Customer may be renting zero or more Videos. One instance of a Video may be being rented by zero or one Customers. Association Multiplicity Examples Employee * Secretary * Company 1..** Company Office Person Manager BoardOfDirectors 0..1 0,3..8 * * Employee BoardOfDirectors Labelling associations Each association can be labelled with a name that gives insight into the meaning of the association Employee * Secretary * w orksFor Company 1..** Manager supervisor Company Office Person BoardOfDirectors 0..1 0,3 ..8 boardMember allocatedTo * * Employee BoardOfDirectors Association Roles When a class is part of an association it plays a role in the relationship. You can name the role that a class plays in an association by placing the name at the class’s association end. Formally, a class role is the set of objects that are linked via the association. class roles project leader Person 1 1..* project member managed project 0..1 assigned project * Project Analyzing and validating associations Many-to-one A company has many employees, An employee can only work for one company. A company can have zero employees E.g. a ‘shell’ company It is not possible to be an employee unless you work for a company Employee * w orksFor Company Analyzing and validating associations Many-to-many A secretary can work for many managers A manager can have many secretaries Secretaries can work in pools Managers can have a group of secretaries Some managers might have zero secretaries. Is it possible for a secretary to have, perhaps temporarily, zero managers? Secretary * 1..** supervisor Manager Analyzing and validating associations One-to-one Company For each company, there is exactly one board of directors A board is the board of only one company A company must always have a board A board must always be of some company BoardOfDirectors Do Not Use Attributes To Relate Concepts Customer Video Worse rentedVideos: List of Video Customer Better ... 1 renter : Customer Rents4 1..* Video ... Reflexive associations It is possible for an association to connect a class to itself successor * Course * prerequisite * * isMutuallyExclusiveWith Navigability One can indicate that an object “knows about” another object it is linked to by using navigation arrows on associations In UML 2.0 one can also explicitly show that one object does not know about the objects it is linked to. The constructs in diagrams 1, 2, and 4 are new to UML 2.0 and thus are most likely not supported by UML tools as yet. •The top pair AB shows a binary association with two navigable ends. •The second pair CD shows a binary association with two non-navigable ends. •The third pair EF shows a binary association with unspecified navigability. •The fourth pair GH shows a binary association with one end navigable and the other non-navigable. •The fifth pair IJ shows a binary association with one end navigable and the other having unspecified navigability. Actions versus associations A common mistake is to represent actions as if they were associations LibraryPatron * * * borrow Loan return * * CollectionItem Bad, due to the use of associations that are actions * borrowedDate dueDate * returnedDate LibraryPatron CollectionItem Better: The borrow operation creates a Loan and the return operation sets the returnedDate What is a Class Diagram? A class diagram describes a structure of classes Key Question: What are the objects of interest in the problem/solution space? their properties (in terms of attributes and operations)? their relationships? An example of a Class Diagram description of problem concepts 0..1 Rents4 Customer address name phoneNumber * VideoStore Rents-from 4 * 1 address name phoneNumber 1..2 HeadOffice Video Stocks4 1 * ID *branchOffice The above is part of a domain model for a video rental system Objects and Links An object is an instance of a class A link is an instance of an association 0..1 Rents4 Customer address name phoneNumber VideoStore Rents-from 4 * 1 address name phoneNumber 1..2 HeadOffice * Video Stocks4 1 * ID *branchOffice Can you draw a valid object diagram for this class diagram? Association: Model to Implementation Student * istakenby 4 Course enrolls Class Student { Course enrolls[4]; } Class Course { Student istakenby[]; } 29 Association: Model to Implementation Student * has 4 Course enrolls Class Student { Course enrolls[4]; } 30 Class Exercise Create a class diagram that reflects concepts for a typical student at a university. Modeling Static Class Relationships Association Aggregation/composition Generalization Dependency 32 Aggregation Aggregation is a special form of association reflect whole-part relationships The whole delegates responsibilities to its parts the parts are subordinate to the whole This is unlike associations in which classes have equal status UML Forms of Aggregation Composition (strong aggregation) parts are existent-dependent on the whole parts are generated at the same time, before, or after the whole is created (depending on cardinality at whole end) and parts are deleted before or at the same time the whole dies multiplicity at whole end must be 1 or 0..1 (weak) Aggregation Composition – black diamond notation Window 1 1 scrollbar Slider 2 1 title 1 Header body 1 Panel OO Relationships: Composition Composition: expresses a relationship among instances of related classes. It is a specific kind of Whole-Part relationship. Whole Class It expresses a relationship where an instance of the Whole-class has the responsibility to create and initialize instances of each Part-class. Class W Class P2 Class P1 Part Classes It may also be used to express a relationship where instances of the Part-classes have privileged access or visibility to certain attributes and/or behaviors defined by the Whole-class. Composition should also be used to express relationship where instances of the Whole-class have exclusive access to and control of instances of the Part-classes. Example Automobile Engine Composition should be used to express a relationship where the behavior of Part instances is undefined without being related to an instance of the Whole. And, conversely, the behavior of the Whole is ill-defined or incomplete if one or more of the Part instances are undefined. Transmission [From Dr.David A. Workman] 36 OO Relationships: Aggregation Container Class Class C Aggregation: expresses a relationship among instances of related classes. It is a specific kind of ContainerContainee relationship. AGGREGATION Class E1 Class E2 Containee Classes Example Apples Bag It expresses a relationship where an instance of the Container-class has the responsibility to hold and maintain instances of each Containee-class that have been created outside the auspices of the Container-class. Aggregation should be used to express a more informal relationship than composition expresses. That is, it is an appropriate relationship where the Container and its Containees can be manipulated independently. Aggregation is appropriate when Container and Containees have no special access privileges to each other. Milk 37 [From Dr.David A. Workman] Aggregation vs. Composition •Composition is really a strong form of aggregation •components have only one owner •components cannot exist independent of their owner •components live or die with their owner e.g. Each car has an engine that can not be shared with other cars. •Aggregations may form "part of" the aggregate, but may not be essential to it. They may also exist independent of the aggregate. e.g. Apples may exist independent of the bag. 38 Modeling Static Class Relationships Association Aggregation/composition Generalization Dependency 39 Generalization/Specialization A generalization (or specialization) is a relationship between a general concept and its specializations. Objects of specializations can be used anywhere an object of a generalization is expected (but not vice versa). Example: Polygon and Ellipse are specializations of Shape Shape Separate Target Style Generalization Polygon Ellipse Spline . .. Rendering Generalizations Generalization is rendered as a solid directed Shape line with a large open arrowhead. Shared Target Style Arrowhead points towards generalization A discriminator can be used to identify the nature of specializations Polygon Ellipse Spline ... Generalization Vehicle venue power power {overlapping} WindPowered Vehicle Truck venue MotorPowered Vehicle Sailboat {overlapping} Land Vehicle Fig. 3-48, UML Notation Guide Water Vehicle An example (generalization) PersonRole 0..2 Person name idNumber RegularFlight * EmployeeRole PassengerRole jobFunction supervisor * * Booking seatNumber * * * SpecificFlight date time flightNumber Object Diagram - Example Organism location * children 0..1 parent Person Organization Engineering:Organization Location=“chicago” Apps:Organization Tools:Organization location=“Wilmington” Location=“chicago” manager employee don:Person charlene:Person location=“Raleigh” location=“denver” 44 Association end constraints Binary and N-ary Associations A binary association relates two classes. An n-ary association relates n (n > 2) classes. N-ary associations can often be modeled as binary associations. Can you interpret the following? Class Diagram Exercise Create a use case diagram and a class diagram using the problem description below. The BirdCage Corporation needs software to aid the management of its business. The corporation builds its business around domestic birds. BirdCage arranges its business around different services with each service being managed by a different company making BirdCage a group of companies. Companies are divided into departments. Services include veterinary services, safekeeping of birds, bird calisthenics and a bird competitions service. In order to streamline its business, BirdCage classifies the veterinary and safekeeping services as medical services. The other two services are regarded as entertainment services. In the future the company hopes to add a number of “Nutritional” services to address the production and sales of food for birds. The corporation classifies birds as either exotic or non-exotic. BirdCage does not provide entertainment services for exotic birds. Owls and crows are non-exotic birds, while macaws, cockatoos and green quakers are exotic. BirdCage seeks to maintain a minimum stock of at least 10 of each type of exotic bird. Modeling Static Class Relationships Association Aggregation/composition Generalization Dependency 49 Dependencies in UML A dependency is a client-server relationship between model elements. A dependency is shown as a dashed arrow between two model elements. The server is at the arrowhead. The arrow may be labeled with an optional stereotype. 50 Dependencies Notation in UML 51 Realization Dependencies 52 Usage Dependencies 53 Objectives Introduce basic class diagram constructs Introduce UML relationships Generalization Association Aggregation/composition Dependency UML Interfaces Interfaces in UML An interface is a named collection of operations that represent the services provided by a class or component. Interfaces do not typically have attributes. Interfaces do not provide implementations for their operations. 55 Example of an interface Interface operation1( ) : Type1 operation2( ) : Type2 operation3( ) : Type3 operation4( ) : Type4 operation5( ) : Type5 56 UML Notation for Interfaces Usage Dependency Realization Dependency An interface may be identified using the <<interface>> keyword preceding the name of the interface. Classes that use the interface can have two types of relationships or dependencies Interface realization Usage 57 UML Notation for Interfaces Usage Interface realization means ProximitySensor implements the operations defined by ISensor. Interface Realization ISensor is called a provided interface for ProximitySensor. Interface usage means TheAlarm uses the operations defined by ISensor. ISensor is called a requiredinterface for TheAlarm. 58 Interfaces: Dependency Provided Interface Realization Dependency Required Interface Usage Dependency 59 Interfaces: Dependency “Ball-and-socket” notation Required Interface Usage Dependency Provided Interface Realization Dependency ISensor 60 What does this model mean? IAlarm is a provided interface for ISensor. ISensor is a provided interface for IAlarm . 61 What does this model mean? IBuzzer is a provided interface for IAlarm . … 62 Summary In this lecture we: Introduced basic class diagram constructs Relationships in UML Association/aggregation/composition/dependency UML Interfaces What’s coming next class? Qu es ti ons? ______________________ Devon M. Simmonds Computer Science Department University of North Carolina Wilmington _____________________________________________________________ 64