OOSE Unit 5
OOSE Unit 5
In the object-oriented design method, the system is viewed as a collection of objects (i.e., entities).
The state is distributed among the objects, and each object handles its state data. For example, in a
Library Automation Software, each library representative may be a separate object with its data and
functions to operate on these data. The tasks defined for one purpose cannot refer or change data
of other objects. Objects have their internal data which represent their state. Similar objects create a
class. In other words, each object is a member of some class. Classes may inherit features from the
superclass.
1. Objects: All entities involved in the solution design are known as objects. For example,
person, banks, company, and users are considered as objects. Every entity has some
attributes associated with it and has some methods to perform on the attributes.
2. Classes: A class is a generalized description of an object. An object is an instance of a class. A
class defines all the attributes, which an object can have and methods, which represents the
functionality of the object.
3. Messages: Objects communicate by message passing. Messages consist of the integrity of
the target object, the name of the requested operation, and any other action needed to
perform the function. Messages are often implemented as procedure or function calls.
4. Abstraction In object-oriented design, complexity is handled using abstraction. Abstraction
is the removal of the irrelevant and the amplification of the essentials.
5. Encapsulation: Encapsulation is also called an information hiding concept. The data and
operations are linked to a single unit. Encapsulation not only bundles essential information
of an object together but also restricts access to the data and methods from the outside
world.
6. Inheritance: OOD allows similar classes to stack up in a hierarchical manner where the lower
or sub-classes can import, implement, and re-use allowed variables and functions from their
immediate superclasses.This property of OOD is called an inheritance. This makes it easier to
define a specific class and to create generalized classes from specific ones.
7. Polymorphism: OOD languages provide a mechanism where methods performing similar
tasks but vary in arguments, can be assigned the same name. This is known as
polymorphism, which allows a single interface is performing functions for different types.
Depending upon how the service is invoked, the respective portion of the code gets
executed.
The Object-Oriented design pyramid specifically emphasizes specific product or system design. Note,
however, that another design layer exists, which forms the base on which the pyramid rests. It
focuses on the core layer the design of the domain object, which plays an important role in building
the infrastructure for the Object-Oriented system by providing support for human/computer
interface activities, task management.
Some of the terminologies that are often encountered while studying Object-Oriented
Concepts include:
1. Attributes: a collection of data values that describe a class.
2. Class: encapsulates the data and procedural abstractions required to describe the content and
behavior of some real-world entity. In other words, A class is a generalized description that
describes the collection of similar objects.
3. Objects: instances of a specific class. Objects inherit a class’s attributes and operations.
4. Operations: also called methods and services, provide a representation of one of the behaviors of
the class.
5. Subclass: specialization of the super class. A subclass can inherit both attributes and operations
from a super class.
6. Superclass: also called a base class, is a generalization of a set of classes that are related to it.
Advantages of OOAD:
1. Improved modularity: OOAD encourages the creation of small, reusable objects that can
be combined to create more complex systems, improving the modularity and
maintainability of the software.
2. Better abstraction: OOAD provides a high-level, abstract representation of a software
system, making it easier to understand and maintain.
3. Improved reuse: OOAD encourages the reuse of objects and object-oriented design
patterns, reducing the amount of code that needs to be written and improving the
quality and consistency of the software.
4. Improved communication: OOAD provides a common vocabulary and methodology for
software developers, improving communication and collaboration within teams.
5. Reusability: OOAD emphasizes the use of reusable components and design patterns,
which can save time and effort in software development by reducing the need to create
new code from scratch.
6. Scalability: OOAD can help developers design software systems that are scalable and can
handle changes in user demand and business requirements over time.
7. Maintainability: OOAD emphasizes modular design and can help developers create
software systems that are easier to maintain and update over time.
8. Flexibility: OOAD can help developers design software systems that are flexible and can
adapt to changing business requirements over time.
9. Improved software quality: OOAD emphasizes the use of encapsulation, inheritance, and
polymorphism, which can lead to software systems that are more reliable, secure, and
efficient.
Disadvantages of OOAD:
1. Complexity: OOAD can add complexity to a software system, as objects and their
relationships must be carefully modeled and managed.
2. Overhead: OOAD can result in additional overhead, as objects must be instantiated,
managed, and interacted with, which can slow down the performance of the software.
3. Steep learning curve: OOAD can have a steep learning curve for new software
developers, as it requires a strong understanding of OOP concepts and techniques.
4. Complexity: OOAD can be complex and may require significant expertise to implement
effectively. It may be difficult for novice developers to understand and apply OOAD
principles.
5. Time-consuming: OOAD can be a time-consuming process that involves significant
upfront planning and documentation. This can lead to longer development times and
higher costs.
6. Rigidity: Once a software system has been designed using OOAD, it can be difficult to
make changes without significant time and expense. This can be a disadvantage in
rapidly changing environments where new technologies or business requirements may
require frequent changes to the system.
7. Cost: OOAD can be more expensive than other software engineering methodologies due
to the upfront planning and documentation required.
In the system analysis or object-oriented analysis phase of software development, the system
requirements are determined, the classes are identified and the relationships among classes are
identified.
The three analysis techniques that are used in conjunction with each other for object-oriented
analysis are object modelling, dynamic modelling, and functional modelling.
Object Modelling
Object modelling develops the static structure of the software system in terms of objects. It
identifies the objects, the classes into which the objects can be grouped into and the relationships
between the objects. It also identifies the main attributes and operations that characterize each
class.
The process of object modelling can be visualized in the following steps −
• Identify objects and group into classes
• Identify the relationships among classes
• Create user object model diagram
• Define user object attributes
• Define the operations that should be performed on the classes
• Review glossary
Dynamic Modelling
After the static behavior of the system is analyzed, its behavior with respect to time and external
changes needs to be examined. This is the purpose of dynamic modelling.
Dynamic Modelling can be defined as “a way of describing how an individual object responds to
events, either internal events triggered by other objects, or external events triggered by the outside
world”.
The process of dynamic modelling can be visualized in the following steps −
• Identify states of each object
• Identify events and analyze the applicability of actions
• Construct dynamic model diagram, comprising of state transition diagrams
• Express each state in terms of object attributes
• Validate the state–transition diagrams drawn
Functional Modelling
Functional Modelling is the final component of object-oriented analysis. The functional model shows
the processes that are performed within an object and how the data changes as it moves between
methods. It specifies the meaning of the operations of object modelling and the actions of dynamic
modelling. The functional model corresponds to the data flow diagram of traditional structured
analysis.
The process of functional modelling can be visualized in the following steps −
• Identify all the inputs and outputs
• Construct data flow diagrams showing functional dependencies
• State the purpose of each function
• Identify constraints
• Specify optimization criteria
Structured Analysis vs. Object Oriented Analysis
The Structured Analysis/Structured Design (SASD) approach is the traditional approach of software
development based upon the waterfall model. The phases of development of a system using SASD
are −
• Feasibility Study
• Requirement Analysis and Specification
• System Design
• Implementation
• Post-implementation Review
Now, we will look at the relative advantages and disadvantages of structured analysis approach and
object-oriented analysis approach.
A state machine models the behavior of an object as it passes through a number of states in its
lifetime due to some events as well as the actions occurring due to the events. A state machine is
graphically represented through a state transition diagram.
States and State Transitions
State
The state is an abstraction given by the values of the attributes that the object has at a particular
time period. It is a situation occurring for a finite time period in the lifetime of an object, in which it
fulfils certain conditions, performs certain activities, or waits for certain events to occur. In state
transition diagrams, a state is represented by rounded rectangles.
Parts of a state
• Name − A string differentiates one state from another. A state may not have any name.
• Entry/Exit Actions − It denotes the activities performed on entering and on exiting the state.
• Internal Transitions − The changes within a state that do not cause a change in the state.
• Sub–states − States within states.
Transition
A transition denotes a change in the state of an object. If an object is in a certain state when an
event occurs, the object may perform certain activities subject to specified conditions and change
the state. In this case, a state−transition is said to have occurred. The transition gives the
relationship between the first state and the new state. A transition is graphically represented by a
solid directed arc from the source state to the destination state.
The five parts of a transition are −
• Source State − The state affected by the transition.
• Event Trigger − The occurrence due to which an object in the source state undergoes a
transition if the guard condition is satisfied.
• Guard Condition − A Boolean expression which if True, causes a transition on receiving the
event trigger.
• Action − An un-interruptible and atomic computation that occurs on the source object due
to some event.
• Target State − The destination state after completion of transition.
Example
Suppose a person is taking a taxi from place X to place Y. The states of the person may be: Waiting
(waiting for taxi), Riding (he has got a taxi and is travelling in it), and Reached (he has reached the
destination). The following figure depicts the state transition.
Events
Events are some occurrences that can trigger state transition of an object or a group of objects.
Events have a location in time and space but do not have a time period associated with it. Events are
generally associated with some actions.
Examples of events are mouse click, key press, an interrupt, stack overflow, etc.
Events that trigger transitions are written alongside the arc of transition in state diagrams.
Example
Considering the example shown in the above figure, the transition from Waiting state to Riding state
takes place when the person gets a taxi. Likewise, the final state is reached, when he reaches the
destination. These two occurrences can be termed as events Get_Taxi and Reach_Destination. The
following figure shows the events in a state machine.
Deferred Events
Deferred events are those which are not immediately handled by the object in the current state but
are lined up in a queue so that they can be handled by the object in some other state at a later time.
Event Classes
Event class indicates a group of events with common structure and behavior. As with classes of
objects, event classes may also be organized in a hierarchical structure. Event classes may have
attributes associated with them, time being an implicit attribute. For example, we can consider the
events of departure of a flight of an airline, which we can group into the following class −
Flight_Departs (Flight_No, From_City, To_City, Route)
Actions
Activity
Activity is an operation upon the states of an object that requires some time period. They are the
ongoing executions within a system that can be interrupted. Activities are shown in activity diagrams
that portray the flow from one activity to another.
Action
An action is an atomic operation that executes as a result of certain events. By atomic, it is meant
that actions are un-interruptible, i.e., if an action starts executing, it runs into completion without
being interrupted by any event. An action may operate upon an object on which an event has been
triggered or on other objects that are visible to this object. A set of actions comprise an activity.
Scenario
Scenario is a description of a specified sequence of actions. It depicts the behavior of objects
undergoing a specific action series. The primary scenarios depict the essential sequences and the
secondary scenarios depict the alternative sequences.
Diagrams for Dynamic Modelling
There are two primary diagrams that are used for dynamic modelling −
Interaction Diagrams
Interaction diagrams describe the dynamic behavior among different objects. It comprises of a set of
objects, their relationships, and the message that the objects send and receive. Thus, an interaction
models the behavior of a group of interrelated objects. The two types of interaction diagrams are −
• Sequence Diagram − It represents the temporal ordering of messages in a tabular manner.
• Collaboration Diagram − It represents the structural organization of objects that send and
receive messages through vertices and arcs.
System Concurrency
Here, concurrency is modelled in the system level. The overall system is modelled as the aggregation
of state machines, where each state machine executes concurrently with others.
Sequential Sub-states
In sequential sub-states, the control of execution passes from one sub-state to another sub-state
one after another in a sequential manner. There is at most one initial state and one final state in
these state machines.
The following figure illustrates the concept of sequential sub-states.
Concurrent Sub-states
In concurrent sub-states, the sub-states execute in parallel, or in other words, each state has
concurrently executing state machines within it. Each of the state machines has its own initial and
final states. If one concurrent sub-state reaches its final state before the other, control waits at its
final state. When all the nested state machines reach their final states, the sub-states join back to a
single flow.
The following figure shows the concept of concurrent sub-states.
Representation in DFD − A process is represented as an ellipse with its name written inside it and
contains a fixed number of input and output data values.
Example − The following figure shows a process Compute_HCF_LCM that accepts two integers as
inputs and outputs their HCF (highest common factor) and LCM (least common multiple).
Data Flows
Data flow represents the flow of data between two processes. It could be between an actor and a
process, or between a data store and a process. A data flow denotes the value of a data item at
some point of the computation. This value is not changed by the data flow.
Representation in DFD − A data flow is represented by a directed arc or an arrow, labelled with the
name of the data item that it carries.
In the above figure, Integer_a and Integer_b represent the input data flows to the process, while
L.C.M. and H.C.F. are the output data flows.
A data flow may be forked in the following cases −
• The output value is sent to several places as shown in the following figure. Here, the output
arrows are unlabelled as they denote the same value.
• The data flow contains an aggregate value, and each of the components is sent to different
places as shown in the following figure. Here, each of the forked components is labelled.
Actors
Actors are the active objects that interact with the system by either producing data and inputting
them to the system, or consuming data produced by the system. In other words, actors serve as the
sources and the sinks of data.
Representation in DFD − An actor is represented by a rectangle. Actors are connected to the inputs
and outputs and lie on the boundary of the DFD.
Example − The following figure shows the actors, namely, Customer and Sales_Clerk in a counter
sales system.
Data Stores
Data stores are the passive objects that act as a repository of data. Unlike actors, they cannot
perform any operations. They are used to store data and retrieve the stored data. They represent a
data structure, a disk file, or a table in a database.
Representation in DFD − A data store is represented by two parallel lines containing the name of the
data store. Each data store is connected to at least one process. Input arrows contain information to
modify the contents of the data store, while output arrows contain information retrieved from the
data store. When a part of the information is to be retrieved, the output arrow is labelled. An
unlabelled arrow denotes full data retrieval. A two-way arrow implies both retrieval and update.
Example − The following figure shows a data store, Sales_Record, that stores the details of all sales.
Input to the data store comprises of details of sales such as item, billing amount, date, etc. To find
the average sales, the process retrieves the sales records and computes the average.
Constraints
Constraints specify the conditions or restrictions that need to be satisfied over time. They allow
adding new rules or modifying existing ones. Constraints can appear in all the three models of
object-oriented analysis.
• In Object Modelling, the constraints define the relationship between objects. They may also
define the relationship between the different values that an object may take at different
times.
• In Dynamic Modelling, the constraints define the relationship between the states and events
of different objects.
• In Functional Modelling, the constraints define the restrictions on the transformations and
computations.
Representation − A constraint is rendered as a string within braces.
Example − The following figure shows a portion of DFD for computing the salary of employees of a
company that has decided to give incentives to all employees of the sales department and increment
the salary of all employees of the HR department. It can be seen that the constraint {Dept:Sales}
causes incentive to be calculated only if the department is sales and the constraint {Dept:HR} causes
increment to be computed only if the department is HR.
Control Flows
A process may be associated with a certain Boolean value and is evaluated only if the value is true,
though it is not a direct input to the process. These Boolean values are called the control flows.
Representation in DFD − Control flows are represented by a dotted arc from the process producing
the Boolean value to the process controlled by them.
Example − The following figure represents a DFD for arithmetic division. The Divisor is tested for
non-zero. If it is not zero, the control flow OK has a value True and subsequently the Divide process
computes the Quotient and the Remainder.
Developing the DFD Model of a System
In order to develop the DFD model of a system, a hierarchy of DFDs are constructed. The top-level
DFD comprises of a single process and the actors interacting with it.
At each successive lower level, further details are gradually included. A process is decomposed into
sub-processes, the data flows among the sub-processes are identified, the control flows are
determined, and the data stores are defined. While decomposing a process, the data flow into or out
of the process should match the data flow at the next level of DFD.
Example − Let us consider a software system, Wholesaler Software, that automates the transactions
of a wholesale shop. The shop sells in bulks and has a clientele comprising of merchants and retail
shop owners. Each customer is asked to register with his/her particulars and is given a unique
customer code, C_Code. Once a sale is done, the shop registers its details and sends the goods for
dispatch. Each year, the shop distributes Christmas gifts to its customers, which comprise of a silver
coin or a gold coin depending upon the total sales and the decision of the proprietor.
The functional model for the Wholesale Software is given below. The figure below shows the top-
level DFD. It shows the software as a single process and the actors that interact with it.
The actors in the system are −
• Customers
• Salesperson
• Proprietor
In the next level DFD, as shown in the following figure, the major processes of the system are
identified, the data stores are defined and the interaction of the processes with the actors, and the
data stores are established.
In the system, three processes can be identified, which are −
• Register Customers
• Process Sales
• Ascertain Gifts
The data stores that will be required are −
• Customer Details
• Sales Details
• Gift Details
The following figure shows the details of the process Register Customer. There are three processes
in it, Verify Details, Generate C_Code, and Update Customer Details. When the details of the
customer are entered, they are verified. If the data is correct, C_Code is generated and the data
store Customer Details is updated.
The following figure shows the expansion of the process Ascertain Gifts. It has two processes in it,
Find Total Sales and Decide Type of Gift Coin. The Find Total Sales process computes the yearly total
sales corresponding to each customer and records the data. Taking this record and the decision of
the proprietor as inputs, the gift coins are allotted through Decide Type of Gift Coin process.
Relationship between Object, Dynamic, and Functional Models
The Object Model, the Dynamic Model, and the Functional Model are complementary to each other
for a complete Object-Oriented Analysis.
• Object modelling develops the static structure of the software system in terms of objects.
Thus it shows the “doers” of a system.
• Dynamic Modelling develops the temporal behavior of the objects in response to external
events. It shows the sequences of operations performed on the objects.
• Functional model gives an overview of what the system should do.
Functional Model and Object Model
The four main parts of a Functional Model in terms of object model are −
• Process − Processes imply the methods of the objects that need to be implemented.
• Actors − Actors are the objects in the object model.
• Data Stores − These are either objects in the object model or attributes of objects.
• Data Flows − Data flows to or from actors represent operations on or by objects. Data flows
to or from data stores represent queries or updates.
Functional Model and Dynamic Model
The dynamic model states when the operations are performed, while the functional model states
how they are performed and which arguments are needed. As actors are active objects, the dynamic
model has to specify when it acts. The data stores are passive objects and they only respond to
updates and queries; therefore the dynamic model need not specify when they act.
Object Model and Dynamic Model
The dynamic model shows the status of the objects and the operations performed on the
occurrences of events and the subsequent changes in states. The state of the object as a result of
the changes is shown in the object model.
Brief History
It was developed in 1990s as an amalgamation of several techniques, prominently OOAD technique
by Grady Booch, OMT (Object Modelling Technique) by James Rumbaugh, and OOSE (Object
Oriented Software Engineering) by Ivar Jacobson. UML attempted to standardize semantic models,
syntactic notations, and diagrams of OOAD.
Object
An object is represented as a rectangle with two sections −
• The top section contains the name of the object with the name of the class or package of
which it is an instance of. The name takes the following forms −
o object-name − class-name
o object-name − class-name :: package-name
o class-name − in case of anonymous objects
• The bottom section represents the values of the attributes. It takes the form attribute-name
= value.
• Sometimes objects are represented using rounded rectangles.
Example − Let us consider an object of the class Circle named c1. We assume that the center of c1 is
at (2, 3) and the radius of c1 is 5. The following figure depicts the object.
Component
A component is a physical and replaceable part of the system that conforms to and provides the
realization of a set of interfaces. It represents the physical packaging of elements like classes and
interfaces.
Notation − In UML diagrams, a component is represented by a rectangle with tabs as shown in the
figure below.
Interface
Interface is a collection of methods of a class or component. It specifies the set of services that may
be provided by the class or component.
Notation − Generally, an interface is drawn as a circle together with its name. An interface is almost
always attached to the class or component that realizes it. The following figure gives the notation of
an interface.
Package
A package is an organized group of elements. A package may contain structural things like classes,
components, and other packages in it.
Notation − Graphically, a package is represented by a tabbed folder. A package is generally drawn
with only its name. However it may have additional details about the contents of the package. See
the following figures.
Relationship
The notations for the different types of relationships are as follows −
Usually, elements in a relationship play specific roles in the relationship. A role name signifies the
behavior of an element participating in a certain context.
Example − The following figures show examples of different relationships between classes. The first
figure shows an association between two classes, Department and Employee, wherein a department
may have a number of employees working in it. Worker is the role name. The ‘1’ alongside
Department and ‘*’ alongside Employee depict that the cardinality ratio is one–to–many. The second
figure portrays the aggregation relationship, a University is the “whole–of” many Departments.
Component Diagram
Component diagrams show the organization and dependencies among a group of components.
Component diagrams comprise of −
• Components
• Interfaces
• Relationships
• Packages and Subsystems (optional)
Component diagrams are used for −
• constructing systems through forward and reverse engineering.
• modeling configuration management of source code files while developing a system using an
object-oriented programming language.
• representing schemas in modeling databases.
• modeling behaviors of dynamic systems.
Example
The following figure shows a component diagram to model a system’s source code that is developed
using C++. It shows four source code files, namely, myheader.h, otherheader.h, priority.cpp, and
other.cpp. Two versions of myheader.h are shown, tracing from the recent version to its ancestor.
The file priority.cpp has compilation dependency on other.cpp. The file other.cpp has compilation
dependency on otherheader.h.
Deployment Diagram
A deployment diagram puts emphasis on the configuration of runtime processing nodes and their
components that live on them. They are commonly comprised of nodes and dependencies, or
associations between the nodes.
Deployment diagrams are used to −
• model devices in embedded systems that typically comprise of software-intensive collection
of hardware.
• represent the topologies of client/server systems.
• model fully distributed systems.
Example
The following figure shows the topology of a computer system that follows client/server
architecture. The figure illustrates a node stereotyped as server that comprises of processors. The
figure indicates that four or more servers are deployed at the system. Connected to the server are
the client nodes, where each node represents a terminal device such as workstation, laptop,
scanner, or printer. The nodes are represented using icons that clearly depict the real-world
equivalent.
OOAD - UML Behavioural Diagrams
UML behavioral diagrams visualize, specify, construct, and document the dynamic aspects of a
system. The behavioral diagrams are categorized as follows: use case diagrams, interaction
diagrams, state–chart diagrams, and activity diagrams.
Use Case Model
Use case
A use case describes the sequence of actions a system performs yielding visible results. It shows the
interaction of things outside the system with the system itself. Use cases may be applied to the
whole system as well as a part of the system.
Actor
An actor represents the roles that the users of the use cases play. An actor may be a person (e.g.
student, customer), a device (e.g. workstation), or another system (e.g. bank, institution).
The following figure shows the notations of an actor named Student and a use case called Generate
Performance Report.
Interaction Diagrams
Interaction diagrams depict interactions of objects and their relationships. They also include the
messages passed between them. There are two types of interaction diagrams −
• Sequence Diagrams
• Collaboration Diagrams
Interaction diagrams are used for modeling −
• the control flow by time ordering using sequence diagrams.
• the control flow of organization using collaboration diagrams.
Sequence Diagrams
Sequence diagrams are interaction diagrams that illustrate the ordering of messages according to
time.
Notations − These diagrams are in the form of two-dimensional charts. The objects that initiate the
interaction are placed on the x–axis. The messages that these objects send and receive are placed
along the y–axis, in the order of increasing time from top to bottom.
Example − A sequence diagram for the Automated Trading House System is shown in the following
figure.
Collaboration Diagrams
Collaboration diagrams are interaction diagrams that illustrate the structure of the objects that send
and receive messages.
Notations − In these diagrams, the objects that participate in the interaction are shown using
vertices. The links that connect the objects are used to send and receive messages. The message is
shown as a labeled arrow.
Example − Collaboration diagram for the Automated Trading House System is illustrated in the figure
below.
State–Chart Diagrams
A state–chart diagram shows a state machine that depicts the control flow of an object from one
state to another. A state machine portrays the sequences of states which an object undergoes due
to events and their responses to events.
State–Chart Diagrams comprise of −
• States: Simple or Composite
• Transitions between states
• Events causing transitions
• Actions due to the events
State-chart diagrams are used for modeling objects which are reactive in nature.
Example
In the Automated Trading House System, let us model Order as an object and trace its sequence. The
following figure shows the corresponding state–chart diagram.
Activity Diagrams
An activity diagram depicts the flow of activities which are ongoing non-atomic operations in a state
machine. Activities result in actions which are atomic operations.
Activity diagrams comprise of −
• Activity states and action states
• Transitions
• Objects
Activity diagrams are used for modeling −
• workflows as viewed by actors, interacting with the system.
• details of operations or computations using flowcharts.
Example
The following figure shows an activity diagram of a portion of the Automated Trading House System.
Implementing Associations
Most programming languages do not provide constructs to implement associations directly. So the
task of implementing associations needs considerable thought.
Associations may be either unidirectional or bidirectional. Besides, each association may be either
one–to–one, one–to–many, or many–to–many.
Unidirectional Associations
For implementing unidirectional associations, care should be taken so that unidirectionality is
maintained. The implementations for different multiplicity are as follows −
• Optional Associations − Here, a link may or may not exist between the participating objects.
For example, in the association between Customer and Current Account in the figure below,
a customer may or may not have a current account.
For implementation, an object of Current Account is included as an attribute in Customer that may
be NULL. Implementation using C++ −
class Customer {
private:
// attributes
Current_Account c; //an object of Current_Account as attribute
public:
Customer() {
c = NULL;
} // assign c as NULL
Current_Account getCurrAc() {
return c;
}
void removeAcc() {
c = NULL;
}
};
• One–to–one Associations − Here, one instance of a class is related to exactly one instance of
the associated class. For example, Department and Manager have one–to–one association
as shown in the figure below.
This is implemented by including in Department, an object of Manager that should not be NULL.
Implementation using C++ −
class Department {
private:
// attributes
Manager mgr; //an object of Manager as attribute
public:
Department (/*parameters*/, Manager m) { //m is not NULL
// assign parameters to variables
mgr = m;
}
Manager getMgr() {
return mgr;
}
};
• One–to–many Associations − Here, one instance of a class is related to more than one
instances of the associated class. For example, consider the association between Employee
and Dependent in the following figure.
This is implemented by including a list of Dependents in class Employee. Implementation using C++
STL list container −
class Employee {
private:
char * deptName;
list <Dependent> dep; //a list of Dependents as attribute
public:
void addDependent ( Dependent d) {
dep.push_back(d);
} // adds an employee to the department
class Project_Manager {
private:
// attributes
Project pj;
public:
void setProject(Project p);
Project removeProject();
};
• One–to–many Associations − Consider the relationship between Department and Employee
having one–to–many association as shown in the figure below.
public:
void addEmployee ( Employee e) {
emp.push_back(e);
} // adds an employee to the department
class Employee {
private:
//attributes
Department d;
public:
void addDept();
void removeDept();
};
Implementing Associations as Classes
If an association has some attributes associated, it should be implemented using a separate class.
For example, consider the one–to–one association between Employee and Project as shown in the
figure below.
Implementation of WorksOn using C++
class WorksOn {
private:
Employee e;
Project p;
Hours h;
char * date;
public:
// class methods
};
Implementing Constraints
Constraints in classes restrict the range and type of values that the attributes may take. In order to
implement constraints, a valid default value is assigned to the attribute when an object is
instantiated from the class. Whenever the value is changed at runtime, it is checked whether the
value is valid or not. An invalid value may be handled by an exception handling routine or other
methods.
Example
Consider an Employee class where age is an attribute that may have values in the range of 18 to 60.
The following C++ code incorporates it −
class Employee {
private: char * name;
int age;
// other attributes
public:
Employee() { // default constructor
strcpy(name, "");
age = 18; // default value
}