[go: up one dir, main page]

0% found this document useful (0 votes)
9 views36 pages

UML Objects2Classes

The document discusses the transition from sequence diagrams to class diagrams in UML, focusing on class structures, relationships, and coding implications. It covers various types of relationships such as association, aggregation, composition, and generalization, along with their coding representations in C++. Additionally, it emphasizes the importance of identifying objects and their relationships in class diagrams, including multiplicity and the implications of ownership in aggregation and composition.

Uploaded by

Patrick Ndungu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views36 pages

UML Objects2Classes

The document discusses the transition from sequence diagrams to class diagrams in UML, focusing on class structures, relationships, and coding implications. It covers various types of relationships such as association, aggregation, composition, and generalization, along with their coding representations in C++. Additionally, it emphasizes the importance of identifying objects and their relationships in class diagrams, including multiplicity and the implications of ownership in aggregation and composition.

Uploaded by

Patrick Ndungu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

From Objects to Class

UML Class Diagram


 Class Diagrams
1.Class Structure from SD to
CD
2.Class Relationships From CD
to Code
Class Diagrams
• Class Structure
 From Sequence Diagrams to Class
Diagrams (Class Relationships):
 Association
 Aggregation and Composition
 Generalisation (Inheritance)
 From Class Diagrams to Code

2
Class Diagram
 Gives an overview of:
 Header and Source files
 Member functions
• UML Class diagram:
Right mouse click on a class to add Type of variable is ‘string’
attributes or functions (i.e. member
variables/functions) in V.Paradigm
Class Name is ‘CPU’

Class CPU has 4 Member Variables


member variables
(display optional)

Class CPU has 8 Member Functions


member functions (display optional)

Accessibility Indicator: Return type of function


‘+’ means public SetManufacturer() is ‘void’
‘-’ means private
‘#’ means protected 3
Function SetModel() takes 1 parameter of type ‘string’
Class Identification
• Identify each object in your sequence
diagram
• For each type of object, create a new
class
• For member functions, look at the
messages sent to objects:
 Each message  member function within the class which
implements that object.
 The parameters of the message (data sent as part of the message)
 the parameters in the member function implementing that
message.
 Any results/data returned by the messages in the sequence diagram
map directly to the return type of the member function 4
Exercise: Map this SD to a class diagram. Identify the member functions,
arguments and returned data

5
UML Class Relationships
• The UML provides three important
types of class relationships:
Association.
Encapsulation in the form of
Aggregation.
Composition.

Generalization.

6
Exercise: Identify the associations in this sequence diagram.

7
Association Relationships
• An association relationship exists where one class
“makes use of” or calls upon the services of another in
some way. Think of the two classes having a ‘working
relationship’.
– A Brake pedal has an association (working relationship) with the brake
lights and servo.
– A CPU has an association (working relationship) with the motherboard.
• Look for objects which send messages to others

Bi - directional association. Objects of Class1 are


able to send messages to Objects of Class2 and
vice-versa. Note no arrows on the association.

Uni - directional association. Objects of Class3


are able to send messages to Objects of Class4 8
but not the other way around
Mapping of Collaborating Objects
to a Class Diagram

Section from a Sequence


Note mapping of message to
Diagram Fns
Maps to this Class Diagram

Result: Uni-
directional
Association

Object3 (represented by Class 3) sends a variety of messages to Object4


(Class 4) but not the other way around, implying a uni-directional
association on the class diagram.

9
Another Example of Mapping
Section from a Sequence Diagram Maps to this Class Diagram

Result: Bi-directional
Association

Note mapping of messages and


implied member variables in both
classes

Object ‘Fred’ (represented by the Class ‘Student’)


sends a variety of messages to Object ‘EECE314’
(represented by the class ‘Course’) and vice-versa, i.e.
messages are sent in both directions and this implies a
bi-directional association on the class diagram
10
Coding an Association
• Association implies one class can send a
message to the other
• Hence, should have a pointer to address it

For example, from the previous class diagram, the implementation of Class
‘Student’ might look like this:
class Student {
Course *theCourse ; // each Student object will have a pointer to a Course
Object
... // it needs initialisation at run time and can be used to send
messages
};

While Class ‘Course’, would look like this (due to the bi-directional
relationship between instances of these two classes).
class Course {
Student *theStudent ; // each Course object will have a pointer to a Student
Object
... // it needs initialisation at run time and can be used to
send messages 11
};
Coding an Association
(Cont’d)
class Student {
public: Course *theCourse ; // pointer to an instance of a Course object

void AddCourse( Course *aCourse) // Fn to create a relationship to a Course object


{
theCourse = aCourse ; // point to the Course object for
this student
theCourse -> theStudent = this ; // IMPORTANT: Now make that
course
} // point back to me as association is bi-directional
}; Pass
Passaapointer
pointerto
tothe
theStudent
Course object
class Course {
public: Student *theStudent ; // pointer to an instance of a Student object

void AddStudent (Student *aStudent) // add a Student object to a


Course
{
theStudent = aStudent ; // point to the Student object for
this Course
theStudent -> theCourse = this ; // IMPORTANT: Now make that
student
} // point back to me as association is bi-directional
};

12
class Course {
class Student { Student *theStudent ;
Course *theCourse ; AddStudent( Student *aStudent)
AddCourse( Course *aCourse) {
{ theStudent = aStudent ;
theCourse = aCourse ;
theCourse -> theStudent = this theStudent -> theCourse =
; this ;
} }
}; };

EECE314's student
pointer Points to
Fred

Object Fred (Instance of a ‘Student’) Object EECE314 (instance of a ‘Course’)

Course *theCourse ; Student


*theStudent ;
Fred's course
pointer points to
EECE314
main()
{
Student Fred(…..) ;
Course EECE314(…) ; Fred can now send messages to
Fred.AddCourse(&EECE314) EECE314 and EECE314 can send
... messages to Fred
}
How do we send a message from one object to the other object at the
end of our relationship? Use the relationship/association pointer

class Student {
public: Course *theCourse ; // pointer to an instance of a Course object
private: // variables for a student
string Name ;
long int ID ;
public:
void PrintStudentDetails() { // prints details of the student and his/her course
cout << “My Name is: ” << Name << ‘\n’ ;
cout << “My ID is: ” << ID << ‘\n’ ;

// the following ‘if’ test is required because we have to make sure that the student
// is pointing to his/her courses, i.e. that there is a valid course object at the end
// of the association IMPORTANT run-time CHECK of validity of association
if( theCourse != NULL) { // provided association is valid
cout << “I am Taking Course ” << theCourse -> GetCourseName() << ‘\n’ ;
cout << “Credit Value ” << theCourse -> GetCourseCredits() << ‘\n’ ;
}
}
...
...
};
Use pointer in this ‘student’ object to
send a message to the object at the
other end of this relationship (i.e. a
course object)
Association Multiplicity
• This brings us to the more general topic of association multiplicity.

• At design time (when we are drawing our class diagrams) we cannot always
predict how many courses a student might ‘enrol on’ or how many students
enrol on each particular course, the number will vary at run-time and hence the
number of objects that may exist at the end of an association could vary.

• We refer to the number of objects at the end of a class association as its


‘multiplicity’ and it is defined for both ends of the association.

• UML class diagrams can capture a variety of different multiplicities as


summarised in the table below.

0..1 Could be 0 or 1 objects (caution: could be 0).


0..* Could be 0 or more objects (caution: could be 0).
* Unknown many (caution: could be 0).
1 Guaranteed always to be exactly 1 object.
n Guaranteed always to be exactly ‘n’ objects (e.g. 5).
1..* Unknown many but at least 1 and maybe more objects.
• Capturing Multiplicity on a class Diagram

‘*’ indicates that a Course may


be associated with many
Students

*
*

‘*’ indicates that a Student may


be associated with many
Courses

To set multiplicity in V.Paradigm, 'right-mouse-


click' on one end of the association and select
'Multiplicity'
Aggregation Relationships
• When one object owns (“has a”)
relationship with other
• The ownership does not affect the message
passing (either can send a message to the
other)

17
What does aggregation mean from a
code perspective?
• Aggregation actually implies the same code as an association, i.e. a pointer in the owner
class pointing to the part that it owns. For example
class Car
{
Engine *MyEngine ; // pointers to point to the ‘part’
Gearbox *MyGearbox;
...
Engine *GetEngine() { return MyEngine ; } // allows for retrieval of the engine
void AddEngine(Engine *theNewEngine ) { // permits ownership of an engine
MyEngine = theNewEngine ; // point to new engine
}
Engine *ExchangeEngine(Engine *theNewEngine ) { // swap an engine for a new one
Engine *temp = MyEngine ; // save pointer to current engine
MyEngine = theNewEngine; // point car to it’s new engine
return temp; // return pointer to old engine for
} // re-use or destruction later
};

• In this respect aggregation has been described as a modelling placebo that is, “Using it
makes you feel good” but doesn’t alter the fact that aggregation is still implemented in
code exactly like an association, nothing different.

• The Car destructor would be altered so that it does not delete the Engine and Gearbox
objects. Similarly, GetEngine() and GetGearbox() functions would be created to detach the
owned objects and return them back to the caller.

18
Composition
• Composition is a stronger form of aggregation where the life times of
the owner and parts are the same, implying that the ‘owner’ is
responsible for the creation and destruction of its ‘parts’.

Composition
Diamond

19
What Does Composition
Mean?
• Parts cannot be detached from the
owner.
• Their lives are the same (one is
part of the other); once owner
destroyed, the parts are also
destroyed.
• Parts cannot be shared amongst
owners (i.e. the multiplicity at the
owner end is always 1).
20
Composition in Code Perspective
class Car
{
private:
Engine *MyEngine ; // ‘Parts’ created by owner when
owner is created
Gearbox *MyGearbox; // and destroyed when owner is
destroyed
public:
Car(…..) { // constructor takes optional args to
initialise Eng/Gearbox
MyEngine = new Engine(…..) ; Owner responsible for creation of
MyGearbox = new Gearbox(…..) ;
} parts

~Car() {
delete MyEngine ; Owner responsible for destruction of
delete MyGearbox ; parts
}
// no functions to permit the returning of a pointer to the engine or gearbox
allowed
// no function to add or swap the engine or gearbox allowed as this implies
sharing of the part
// all functions to manipulate Engine and Gearbox from outside the Car
class
// and must go through the car class e.g.
Access to PartsnewGear);
void ChangeGear( int newGear) { MyGearbox->ChangeGear( is via the
}
void StartEngine() { MyEngine -> Start(); } Owner (Car) only
void StopEngine() { MyEngine->Stop(); } 21
};
Generalisation
• In UML, this is how we create ‘Kind-of’ relationships which
implies two things:

 Inheritance
 Substitutability.

• Inheritance  derived or child


classes get it from base/parent
• Substitutability  child or derived
class could substitute base/parent

22
Generalisation (inheritance). This Generalisation (inheritance). This
means that ‘AMD CPU’ is a ‘kind-of’ means that ‘Intel CPU’ is a ‘kind-of’
CPU. It also means that ‘AMD CPU’ CPU. It also means that ‘Intel CPU’
is a substitute for a CPU is a substitute for a CPU

‘Mobile Athlon 64’ is a ‘kind-of’ AMD CPU. It also means ‘Core 2 Duo’ is a ‘kind-of’ Intel CPU. It also means
that ‘Mobile Athlon 64’ is a substitute for an ‘AMD CPU’ that ‘Core 2 Duo’ is a substitute for an ‘Intel CPU’
(but not an Intel CPU) and is also a substitute for a ‘CPU’ (but not an AMD CPU) and is also a substitute for a
‘CPU’
Through the process of inheritance, all classes lower in
the hierarchy inherit the member functions and Through the process of inheritance, all classes lower
variables of all classes higher up, and can add or in the hierarchy inherit the member functions and
redefine operations thus an Athlon 64FX can perform variables of all classes higher up, and can add or
Reset(), Run() and Interrupt() or could redefine those redefine operations thus a Core 2 can perform
operations to work in different ways to the base class Reset(), Run() and Interrupt() or could redefine those
CPU operations to work in different ways to the base
What does inheritance means in terms of Code
C++ code stating that ‘IntelCPU’ is derived from ‘CPU’, the
‘public’ means that the interfaces of the base class ‘CPU’
are available to the user of an ‘IntelCPU’

Derived class constructor calls base class


class IntelCPU : public CPU { constructor to initialise base class member
public: variables
IntelCPU(…..) : CPU(….) { /* constructor calls base class constructor */ }
// new or overridden member functions and/or variables
};

class AMDCPU : public CPU {


public:
AMDCPU(…..) : CPU(….) { /* constructor calls base class constructor */ }
// new or overridden member functions and/or variables
};

class IntelCoreDuo : public IntelCPU {


public:
IntelCoreDuo(…..) : IntelCPU(….) { /* constructor calls base class constructor */ }
// new or overridden member functions and/or variables
};
Base class pointer can point to a
Now we can create code like this derived class object because the
derived class object is a valid
substitute for the base class
int main()
{
CPU *theCPU = new IntelCoreDuo(…) ;

theCPU ->reset() ;
theCPU ->run() ;
};

 Identify as many components as you can that go to make up a desktop


PC and identify the relationships between them and where relevant
their multiplicities, don’t forget to include things like different kinds of
CPU, cases, disk drives motherboards etc.
 Now draw a class diagram to represent them and show how those
relationships would be mapped to code (ignore member variables and
functions – just capture the code to represent the relationships.
IBM Rational Software Valid
transformation sources
http://www.ibm.com/support/knowledgecenter/SS8PJ7_8.5.1/
com.ibm.xtools.transform.uml2.cpp.doc/topics/cucpptransf.html

26
IBM Rational Software Valid
transformation sources

27
Summary of Class
relationship
• In a system a class may be related
to different classes, following are
the different relation ship.
• Association (knows a)
• Dependency (uses a)
• Composition (owns a) [ Composed
of ]
• Aggregation (has a)
• Inheritance (is a)
28
Different Multiplicity in a relation

“0..1” No instances, or one


instance (optional, may)
“1” Exactly one instance
“0..* or *” Zero or more instances
“1..*” One or more instances (at
least one)

29
Association
One object is aware of another; it contains a pointer or
reference to another object.

Representaion

C++ Example
1. Class X {
2.
3. X(Y *y) : y_ptr(y) {}
4.
5. void SetY(Y *y) { y_ptr = y; }
6.
7. void f() { y_ptr->Foo();}
8. ----
9. Y *y_ptr; // pointer
10. };
30
Dependency
One class depends on another if the independent class is a
parameter variable or local variable of a method of the dependent
class

Representaion

C++ Example

• class X {
• ...
• void f1(Y y) {…; y.Foo(); }
• void f2(Y *y) {…; y->Foo(); }
• void f3(Y &y) {…; y.Foo(); }
• void f4() { Y y; y.Foo(); …}
• void f5() {…; Y::StaticFoo(); }
• ...
• };
31
Aggregation
Aggregation can occur when a class is a collection or
container of other classes, but where the contained classes
do not have a strong life cycle dependency on the container
—essentially, if the container is destroyed, its contents are
not. You may have confusion between aggregation and
association .Association differs from aggregation only in that
it does not imply any containment.

Representaion

• class Window
• {
• public:
• //...
• private:
• vector<Style*> itsStyle;
• };
32
Composition
Composition is the stronger form of aggregation. Composition can occur
when a class is a collection or container of other classes, but where the
contained classes have a strong life cycle dependency on the container—
essentially, if the container is destroyed, its contents are also destroyed

Representation
• class X {
• ...
• Y a; // 1; Composition
• Y b[10]; // 0..10; Composition
• };

• class X {
• X() { a = new Y[10]; }
• ~X(){ delete [] a; }
• ...
• Y *a; // 0..10; Composition
• };

• class X {
• ...
• vector a;
• };
33
Inheritance (Generalization)
In Inheritance relationship a class is derived
from another class. There is a “is a” relationship
between two classes.

Representation:

Example:
// Base class Shape // Derived class
class Shape class Rectangle: public Shape, {
{ public: public:
void setWidth(int w) int getArea()
{ width = w; } {
void setHeight(int h) return (width * height);
{ height = h; } }
protected: int width; int height; }; };

34
References for UML Soft Ware
• Visual Paradigm
– https://www.visual-paradigm.com/
• IBM Rational SW:
http://www.ibm.com/developerworks/rational/library/769.html
• Gliffy: https://www.gliffy.com/uses/uml-
software/
• https://bellekens.com/uml-best-practices
• StartUML http://staruml.io/
• Violet Free UML Editor:
http://alexdp.free.fr/violetumleditor/page.php

35
Java Example: Hash references instead of Pointers
Dereferencing a null:

first.growl(); // ERROR, first is null.


third.growl(); // ERROR, third has not been initialized.

Aliasing Problem:
third = new Tiger();
first = third;

second = third; // Possible ERROR. The old value of second is lost.

36

You might also like