COMP1002 and INFO1003 Object Technology Lecture Notes

advertisement
Object Technology Lecture 2 Notes
Contents
Week 1 - Object Technology Overview ............................................................................................... 3
Learning outcomes ........................................................................................................................... 3
Definition and example .................................................................................................................... 3
Learning notes .................................................................................................................................. 3
Case Study ........................................................................................................................................ 3
Week 2 - Classes, Instances, Operations, Methods and Messages ....................................................... 4
Class used - Fridge ........................................................................................................................... 4
Learning outcomes ........................................................................................................................... 4
Definitions and examples ................................................................................................................. 4
Learning notes for Fridge Class ....................................................................................................... 5
Week 2 continued – more examples ..................................................................................................... 8
Classes used - Student and Module .................................................................................................. 8
Learning Outcomes .......................................................................................................................... 8
Definitions and examples ................................................................................................................. 8
Learning notes for Student and Module Classes ............................................................................. 9
Week 3 - Classes, Instances, Operations, Methods and Messages ..................................................... 11
Classes used - LoyaltyCard and Person, BankAccount and BankCustomer................................... 11
Learning Outcomes ........................................................................................................................ 11
Definitions and examples ............................................................................................................... 11
Learning notes for LoyaltyCard and Person Classes ................................................................... 11
Tracing a set of use cases for LoyaltyCard and Person Classes ................................................... 12
Learning Notes for BankAccount and BankCustomer Classes .................................................. 13
Use Cases for Tracing..................................................................................................................... 13
Week 4 - From Use-Cases to Sequence Diagrams to Implementation (1).......................................... 15
Classes used - LoyaltyCard and Person, Student and Module ........................................................ 15
Learning Outcomes: ....................................................................................................................... 15
Definitions and examples ............................................................................................................... 15
Learning notes ................................................................................................................................ 15
Notes for Sequence Diagram for LoyaltyCard and Person use-cases .......................................... 15
Example of a Sequence Diagram .................................................................................................... 16
Notes on Sequence Diagrams for Student and Module use-cases................................................. 17
Week 5 - From Use-Cases to Sequence Diagrams to Implementation (2).......................................... 19
Classes used - StoreCard and StoreCustomer, BankAccount and BankCustomer ......................... 19
Learning Outcomes: ....................................................................................................................... 19
Definition and example .................................................................................................................. 19
Notes for Sequence Diagram for StoreCustomer and StoreCard use-cases ................................ 19
Notes for Sequence Diagram for BankCustomer and BankAccount use-cases ........................... 20
Sequence Diagram for creating a BankAccount............................................................................ 20
Crediting an Account ...................................................................................................................... 20
Sequence Diagram to represent transferring from one Account to another .................................... 21
Week 6 - Inheritance........................................................................................................................... 22
Learning Outcomes: ....................................................................................................................... 22
Definitions and example ................................................................................................................. 22
Example .......................................................................................................................................... 23
Inheritance and the Person Hierarchy ............................................................................................ 24
Java Code Examples ....................................................................................................................... 25
Inheritance and the LoyaltyCard Hierarchy .................................................................................. 26
Week 7 - Aggregation - Whole Part Association (1) .......................................................................... 27
Learning Outcomes: ....................................................................................................................... 27
Definitions and example ................................................................................................................. 27
Learning notes ................................................................................................................................ 27
The BankAccountBase Aggregation ............................................................................................. 29
Week 8 - Composition - Whole Part Association (2) ......................................................................... 31
Learning Outcomes: ....................................................................................................................... 31
Definitions and example (a reminder) ............................................................................................ 31
Learning notes ................................................................................................................................ 31
© De Montfort University
Page 1
Object Technology Lecture 2 Notes
The Bank Composition .................................................................................................................. 33
Use-case - Adding a new Customer .............................................................................................. 34
Use-case - A Customer opens a new CurrentAccount ................................................................ 35
Use-case - Make a Deposit ............................................................................................................. 35
Week 9 - Coursework ......................................................................................................................... 36
Learning outcomes ......................................................................................................................... 36
Resources........................................................................................................................................ 36
Week 10 - Encapsulation .................................................................................................................... 37
Learning Outcomes ........................................................................................................................ 37
Learning notes ................................................................................................................................ 37
Definitions and example ................................................................................................................. 37
Why encapsulation ? ....................................................................................................................... 37
Tasks ............................................................................................................................................... 38
Discussion ...................................................................................................................................... 38
Week 11 & Week 12 - Coursework .................................................................................................... 42
© De Montfort University
Page 2
Object Technology Lecture 2 Notes
Week 1 - Object Technology Overview
Learning outcomes
At the end of this lecture, you should be able to:
 Identify and comprehend the meaning of some key "Object Oriented" or "OO" words as used in
the diagram – Class, Association, Aggregation, Inheritance, Generalisation, Specialisation,
Multiplicity, Roles, Encapsulation, Abstraction etc.
 Identify, from a case study, the key features of a system such as the people, structures and
processes and the relationships between them.
 Construct a Model of a system by identifying and representing the features and relationships of
that system in a UML (Unified Modelling Language) class diagram.
 Compare and contrast the model derived in the lecture with a pre-prepared solution.
Definition and example
UML (The Unified Modelling Language)
"A way of representing models produced during the development process. A modelling language is
usually diagrammatic but can be text based."
Model
"A simplification of reality, created in order to gain a better understanding of the system being
created."
"A representation of all or part of a problem or the system designed to solve it"
UML models used in OO allows system users, system designers and programmers to gain a
common idea of what an existing system does and what a new system might do.
UML models used in OO allows system users, system designers and programmers to describe
a problem and possible solutions.
Learning notes
This is an introductory exercise into the analysis of a problem to do with tracking student enquiries,
admissions and module results. Analysis involves the investigation of the variety of ways problems are
currently solved. We also need to understand what is required of any new system. Analysts build
models showing the essential features of a system, these are often drawn as diagrams.
The case study refers to "real" instances or objects involved in the process of making enquiries and
admissions etc. Initially attempt to identify objects (people and things) and their associations that are
relevant to tracking enquiries, admissions and student results etc. These can be drawn and discussed as
objects. Questions and discussion is more important than how correct the answers are.
Objects with a similar behaviour should be classified into classes. Then a hand drawn Unified
Modelling Language class diagram is to be derived. A pre-prepared solution can be compared with
this diagram and any modelling differences can be discussed.
Case Study
De Montfort University (DMU) receives many enquires from prospective students. Often people ask
about courses related to one subject such as Computing but some ask about studying more than one
subject such as Computing and Accounting. An enquiry about Computing and Accounting is passed to
the admissions unit in the Faculty of Business and Law.
Single honours modular degrees, HND and other types of courses are advertised, each lead to a named
award at DMU. Jane eventually enrolled at DMU on a course called “Computing & Technology”.
Many of the modules Jane studies are also taught on a variety of other courses in the Faculty of
Computing Sciences and Engineering.
Peter is a member of staff based in the Department of Information Systems. Peter teaches modules
covering databases and project management. Peter is a mentor for some Technology "joint" students including Jane. Jane will study eight modules per year but will probably not be taught by Peter. At the
end of the first semester Jane will discuss her module results with her mentor.
© De Montfort University
Page 3
Object Technology Lecture 2 Notes
Week 2 - Classes, Instances, Operations, Methods and Messages
Class used - Fridge
Learning outcomes
At the end of this lecture, you should be able to:
 Explain the difference between Class and Instance/Object and Operation, Method and Message
 Read a Class Diagram and identify the components and constituent parts of the components Class
name, attributes and operations
 Read HTML class documentation and select methods and send messages to instances to solve
problems specified as a series of use-cases
 Complete a simple Java program to implement, execute and test solutions to problems by
declaring variables, creating instances and sending messages
Definitions and examples
Class
“A description of a group of objects that share the same attributes, operations, relationships and
meaning. A template or factory for creating objects.”
A Fridge class defines objects that have attributes capacity, temperature and contents. Setting
the temperature is an operation that all objects of class Fridge share.
Instance / Object
“An object of a particular class.”
myFridge could be a Fridge object with a capacity of 10 items, a temperature of 2 degrees,
which contains Milk and Eggs
yourFridge might be a Fridge object that is empty and is at a temperature of 5 degrees
Attribute
" A feature of an object representing part of its state"
Each Fridge object has three attributes - temperature, capacity and contents. The state of a
Fridge object at a particular time could be that it is at a temperature of 1 degree, contains
some "milk" and "eggs" and it has a capacity of 12 items.
Operation
“A procedure or function defined as part of a class.”
The term operation defines the name of this function and what it does not how it does it
Setting the temperature of a Fridge object to a specified value is defined as
public void setTemperature(int temperature)
This is an operation defined in the class Fridge to be applied to any Fridge object.
Method
"The implementation of a procedure or function defined as part of a class.”
This term defines the implementation of the procedure - how it does what it does.
The method that implements the operation to set the temperature of a fridge is:
public void setTemperature(int temperature)
{ if((temperature >= minTemp) && (temperature <= maxTemp))
this.temperature = temperature;
}
Message
"A request to an object to execute one of its methods."
myFridge.setTemperature(2) is a message to the Fridge object myFridge to set its
temperature to 2.
The format is
<receiver of message>.<message>
<receiver>.<messageName><parameter(s)>
myFridge.setTemperature(2)
© De Montfort University
Page 4
Object Technology Lecture 2 Notes
Use-case
"The functionality that a system will offer from the user’s perspective”
Use-cases for a Fridge object must include allowing items to be stored in the Fridge and the
temperature of the Fridge adjusted. It must be possible to find out what is in the Fridge, its
temperature, how much space there is etc. These requirements are obtained via discussion
with the users of the existing and proposed Fridge class, (see ‘real’ Use-case examples below)
Learning notes for Fridge Class
A refrigerator is a common household item designed to keep food fresh. Many manufacturers make
fridges to different specifications. Some have freezer compartments others have drinks dispensers.
Most have salad sections and shelves and come in a variety of sizes, colours and prices.
This model of a fridge represented by the Fridge class is deliberately over-simplified and just three
attributes have been implemented. Operations defined include only basic ones to add and remove
items and to change and determine the state of the fridge (the values of its three attributes). The
fridge's capacity attribute is simply the (whole) number of items it can hold and not its cubic capacity.
Its contents are represented by strings of characters not items with attributes such as size and sell-bydate. Its temperature is a simple whole number representing a temperature in degrees C.
This simple Fridge class allows us to simulate the behaviour of fridges. We can create fridge objects
and send messages to these objects and examine their behaviour and state.
There are three types of document that should be read in order to understand the Fridge.
You should read
1. the UML Class Diagram for the Fridge Class
2. the Java Class HTML documentation for
the instance creation operations (called 'constructors')
public Fridge(int capacity, int temperature)
public Fridge(int capacity)
public Fridge()
and the operations such as
public void addItem(String item)
3. the Java code for methods such as
public void addItem(String item)
Use-case
Also important are use-cases. These are 'real' examples of how users perceive the Fridge.
An analyst might obtain the following statements from Fridge users:






"I live by myself so I only need a small fridge that I can keep a few things in"
"We like our milk cold so we need to be able to set it to a low temperature in summer"
"I always buy the cheapest fridge as I do not have much spare cash"
"I want to be able to get at things easily when I need to take them out"
"I always look to see how much space there is before I go shopping"
"I want one to match the rest of my kitchen"
In the case of the Fridge model class not all of these use-cases have been implemented.
 Which are they?
 How could they be implemented?
 Suggest some other possible use-cases.
The Java program on the following page creates/constructs a Fridge object and then alters its state.
© De Montfort University
Page 5
Object Technology Lecture 2 Notes
Read the program carefully and add any notes to explain what each line does
Write down the temperature, capacity and contents of the fridge at each of the three points shown in the
program.
import objects.Fridge;
// Allow the program to use the methods in the Fridge class
class FridgeExample
{ // This program creates a Fridge object and then alters it.
public static void main (String args[])
{
Fridge myFridge;
// Declare a variable for a Fridge object
myFridge = new Fridge(8,1);
// temperature =
// capacity =
// contents =
myFridge.show();
myFridge.setTemperature(-2);
// temperature =
// capacity =
// contents =
myFridge.show();
myFridge.addItem("Cheese");
// temperature =
// capacity =
// contents =
myFridge.show();
}
}
Your tutor will compile and run this program for you to check your answers
1.
How many different messages are used in the program?
2.
How many parameters appear in the program altogether?
3.
What does the symbol // represent?
4.
What does the line public static void main (String args[]) tell you?
5.
On the Object Diagram below show the actual values of each of the attributes of myFridge to
show its state just before the final myFridge.show() message is sent
myFridge : Fridge
temperature : int
=
capacity
: int
=
contents
: Collection
=
© De Montfort University
Page 6
Object Technology Lecture 2 Notes
import objects.Fridge; // Allow the Fridge class to be used
class FridgeLecture
{ public static void main (String args[])
{
/* Declare and create a fridge object. Then write a program that
implements this series of use-cases.
If a message should change your fridge object check by sending a
show() message to display the state of the fridge. */
// Three Students in a shared house get a fridge from the landlord.
// The fridge is small and can hold up to 5 items.
// They switch it on setting the temperature to 1 degree.
// One student buys some eggs, milk and beer for the fridge then
// goes out.
// Another student opens the fridge takes out and drinks all of the
// milk. He also decided to chill the beer by setting the
// temperature to -1.
// The first student comes back with some cereal and looks to see
// if there is any milk in the fridge.
// The second student admits to drinking the milk and replaces it
// and also adds some butter.
// How many items are there in the fridge at this point?
// Is the fridge full?
// A third student brings home some cooked meat and tomatoes and
// puts them all in the fridge.
} // End of Main
} // End of Class
© De Montfort University
Page 7
Object Technology Lecture 2 Notes
Week 2 continued – more examples
Classes used - Student and Module
Learning Outcomes
this is an extension to the lecture, to be started as a lecture and completed in the students own time as
private study …
Definitions and examples
Class
"A description of a group of objects that share the same attributes, operations, relationships and
meaning. A template or factory for creating objects"
A Student class defines objects that have attributes name, gender and age and modules.
Registering for a module is an operation that all objects of class Student share.
Object / Instance
"An object that belongs to a particular class"
studentA is a Student object with a name "Anil" , age 19, who is male 'M' who is registered
to take one module module1 ("COMP1004","Networking");
Attribute
" A feature of an object representing part of its state"
Student objects have the attributes name (String), age (int) and gender (char) that all Person
objects have plus a modules attribute to represent the modules that the student has registered
to take. Module objects have two (String) attributes representing the module's code and title.
See Object/Instance for example of attributes and values.
Operation
"A procedure or function defined as part of a class."
This term defines the name of this function and what it does not how it does it
The operation to register a Student on a Module is defined as
public void registerForModule(Module module) and is an operation defined
in the class Student to be applied or sent to any instance of Student.
Method
"The implementation of a procedure or function defined as part of a class.”
This term defines the implementation of the procedure - how it does what it does.
public void registerForModule(Module module)
{ if (!this.hasRegisteredForModule(module)&& this.canTakeAnotherModule())
this.addModule(module);
}
is the method that implements the operation to register a Student on a Module.
Message
"A request to an object to execute one of its methods."
studentA.registerForModule(moduleX) is a message to the Student object
studentA to register for Module moduleX.
The format is
<receiver of message>.<message>
<receiver>.<methodName><parameter(s)>
studentA.registerForModule(moduleX)
© De Montfort University
Page 8
Object Technology Lecture 2 Notes
Use-case
"The functionality that a system will offer from the user’s perspective”
Use-cases for this case study include: A student must be able to register for and withdraw
from modules. A student must be able to find out the number of modules on which he or she
is currently registered. When registering a student must not be able to register for more than a
maximum number of modules nor be able to register for the same module twice
Use-case scenario
"A particular variant of a use-case describing one particular sequence of events that might occur."
Register for a module :A student successfully registers for a module.
A student attempts to register for a module when he is already registered for the maximum
number of modules allowed.
A Student attempts to resister for a module when he is already registered for that module.
Learning notes for Student and Module Classes
Students typically have many more attributes than those used in this model. Analysis would have
shown that the addresses and phone numbers (home and term time) would be needed as would a
student's previous qualifications, referees, UCAS number etc.
For a module object it would be necessary to keep a record of the students who had registered for the
module, the module timetable, the tutors on the module, the module content, how it is assessed etc
In such cases it is vital that the analyst abstracts from the information only those elements that need to
be modelled in order to solve the particular problems involved. In this case the objective was simply to
show how two classes could work together and the user (in this case one of your lecturers) decided that
all he wanted was to allow students to register for and withdraw from modules and for the association
to be in just one direction - from student to module.
Both the Student and Module classes are deliberately simplified.




Only name, gender, age and modules are recorded for a Student
Only the module code number and title are recorded
Modules may be created and displayed.
Students may be created, and perform operations based on registering and withdrawing from
modules.
To understand the Classes Student and Module you should read
 the UML Class Diagram for the Student and Module Classes
 the Java Class HTML documentation for
the instance creation operations
public Module( String code, String title)
public Student(String name, int age, char gender)
the operations
public void registerForModule(Module module)
 the Java code for
the public methods
public boolean hasRegisteredForModule(Module module)
public int numberOfModules()
the private methods
private void addModule(Module module)
private boolean canTakeAnotherModule()
The program on the following page creates two Student objects and three Module objects, registers
the student for both modules then withdraws the student from one of the modules.
© De Montfort University
Page 9
Object Technology Lecture 2 Notes
Read the program carefully and add any notes to explain what each line does.
At the bottom of the page draw an Object Diagram to show the objects created by this program.
import objects.Student;
import objects.Module;
class StudentModuleLecture
{ public static void main (String args[])
{
System.out.println();
Student studentA = new Student("Anil",19,'M');
Student studentB = new Student("Nita",22,'F');
Module module1 = new Module("COMP1004","Networking");
Module module2 = new Module("CSCI1006","Programming in C");
Module module3 = new Module("CSCI1003","Programming in Java");
studentA.show();
studentB.show();
studentA.registerForModule(module1);
studentA.registerForModule(module2);
studentA.registerForModule(module3);
studentB.registerForModule(module2);
studentB.registerForModule(module3);
studentA.show();
studentB.show();
studentA.withdrawFromModule(module2);
studentA.show();
studentB.show();
}
}
Your tutor will compile and run this program for you to check your answers
Object Diagram
: Module
: Student
name
age
gender
: String
: int
: char
code : String =
title : String =
=
=
=
modules : Module[ , , ,…]
: Module
code : String =
title : String =
: Student
name
age
gender
: String
: int
: char
=
=
=
: Module
code : String =
title : String =
modules : Module[ , , ,…]
© De Montfort University
Page 10
Object Technology Lecture 2 Notes
Week 3 - Classes, Instances, Operations, Methods and Messages
Classes used - LoyaltyCard and Person, BankAccount and BankCustomer
Learning Outcomes
At the end of this lecture, you should confidently be able to:
 Explain the difference between Class and Object/Instance, Operation, Method and Message
 Read a Class Diagram and identify the components and constituent parts of the components
(Class name, attributes and operations)
 Read HTML class documentation, select methods and send messages to instances to solve
problems specified as a series of use-cases
 Complete a simple Java program to implement, execute and test solutions to problems by
declaring variables, creating instances and sending messages
Definitions and examples
Association
“A link with a meaning between classes”
A LoyaltyCard is owned exactly one Person.
A Person can own zero or one LoyaltyCard.
Multipicity
“The number of objects in each class that are allowed to participate in the association”
A BankAccount is owned exactly one BankCustomer.
A BankCustomer may own zero or one to three BankAccounts.
Navigation
“The direction in which an association between objects may operate. The direction of navigation is the
direction in which messages may be sent.”
The association between a LoyaltyCard and Person is navigable from LoyaltyCard to Person
ONLY. A LoyaltyCard object may send messages to its owner, a Person object, but a Person
may NOT send messages to a LoyaltyCard.
The association between a BankCustomer and BankAccount is navigable in BOTH directions.
It is possible for a BankAccount object to send messages to the owner of an account and for a
BankCustomer object to send message to each BankAccount owned.
Learning notes for LoyaltyCard and Person Classes
The LoyaltyCard class defined here is based on a typical store where for each pound spent a point is
stored on the card. Each 250 points awarded can be exchanged for a £2.50 voucher. You are simply
expected to be able to understand what the operations addPoints, takeVouchers etc. do in terms of the
results they produce and return and how to use them to implement solutions to a series of simple usecases.
"A Person can own zero or one LoyaltyCard",
in other words a person may have a card or no card at all,
"A LoyaltyCard is owned exactly one Person",
a LoyaltyCard on the other hand, cannot exist without a person to own it.
The link between the LoyaltyCard and person classes is ONE WAY. For a given card it is possible to
determine the Person who owns it. However for a given Person it is not possible to find out anything
about any card they may own.
The model of the Loyalty card has three attributes: the number of points on the card (an int), the card
number (an int automatically generated) and the owner of the card (a Person object)
Predicting the results that a program should produce is important in order to determine its correctness.
Tracing the execution of program will be carried out to predict expected results and show how objects
change their state (how the values of the attributes change).
© De Montfort University
Page 11
Object Technology Lecture 2 Notes
To understand the Classes LoyaltyCard and Person you should
 Read the Class Diagram for the LoyaltyCard and Person Classes
Note this association is navigable one-way only
 Read the Java Class HTML documentation for the addPoints and takeVouchers operations in the
LoyaltyCard Class
 Read the Java code for addPoints and takeVouchers operations in the LoyaltyCard Class
Tracing a set of use cases for LoyaltyCard and Person Classes
Jane, a 25 year old business woman, obtains a loyalty card. She spends £100 on the day she gets it and
over the next few weeks spends the following sums £230, £80, £375, £214. After each transaction she
takes any vouchers she is able to.
1. In the table below write down the attribute values of the LoyaltyCard after each week’s activity.
2. Write a Java program to implement the above and verify your predicted results.
Week
1
2
3
4
5
Use case
spend money
take vouchers
spend money
take vouchers
spend money
take vouchers
spend money
take vouchers
spend money
take vouchers
Amount
spent
100
CardNumber
1234
230
80
375
214
Owner
ownerA
Points
100
100
330
80
160
160
535
35
249
249
Vouchers
taken
0
1
0
2
0
import objects.LoyaltyCard;
import objects.Person;
class LoyaltyCardLecture
{ public static void main (String args[])
{
/*
Jane, a 25 year old business woman, obtains a loyalty card.
She spends £100 on the day she gets it and over the next few
weeks spends the following sums £230, £80, £375, £214.
After each transaction she takes any vouchers she is able to.
*/
} // End of main method
} // end of class
© De Montfort University
Page 12
Object Technology Lecture 2 Notes
Learning Notes for BankAccount and BankCustomer Classes
The BankAccount class modelled here is very simple. There are three attributes: the account number
(an int automatically generated), a balance (a decimal number - a double) and the owner (a
BankCustomer object). There is no overdraft limit (so the balance may be increased and decreased
without limit), or any other attribute often linked with bank accounts. The operations defined include
crediting (putting money into) and debiting (taking money out) of an account.
The BankCustomer class modelled has the same attributes as the Person class plus an additional
accounts attribute, to represent the BankAccounts owned (the maximum is 3). A BankAccount must be
owned by exactly one BankCustomer, in this model joint accounts are not allowed.
To understand the Classes BankAccount and BankCustomer you should
 Read the UML Class Diagram for the BankAccount and BankCustomer Classes
 Note this association is navigable in both directions - how is this significant?
 Read the Java Class HTML documentation for all operations including credit, debit and transfer.
 Note that the methods increaseBalance and decreaseBalance are private to all BankAccount
objects and so may not be directly sent to these objects. Instead the methods credit and debit
should be used. These return Strings with messages showing the success or otherwise of the
method and these can be displayed for example by: System.out.println(account.debit(30));
Use Cases for Tracing
Celia aged 46, is a BankCustomer. She has a bank account in which she has £450. Brian, Celia’s son
aged 18, wants to become a BankCustomer. He decides to open a bank account but has no money. His
mother gives Brian £50 to put into his new account. She later transfers £200 into Brian’s account. Celia
tries to close her account but fails. Why does she fail? Brian checks his account’s to see if he has gone
overdrawn. Celia checks her account number. Celia then withdraws £280 from her account to pay a
bill. Brian spends £30. Brian helps his mum by transferring enough into her account to enable her to
pay her bill that she then pays. Brian then empties his account and closes it. Celia later puts £200 into
her account and tries to repay her son by transferring to his account the amount he lent her plus £20.
(Why does this fail?)
1. Trace this use-case in terms of the two accounts involved using the table provided.
2. Write a Java program to implement this use case to verify your predictions against the actual results
produced.
Use-case
Create Brian (B)
Create Celia (C)
Create B’s acc
Create C’s acc
Deposit 50 in B’s acc
Transfer 200 C - B
Close C’s acc
Get balance B’s
Get Acc # Celia’s
Withdraw 280 C
Withdraw 30 B
Transfer ? B - C
Pay Bill C
Empty B’s acc
Close B’s acc
Deposit 200 C
Transfer ? C - B
acc #
Account X
owner balance
1001
cust1
© De Montfort University
450
open
acc #
Account Y
owner balance
1002
cust2
open
Y
200
0
50
250
Y
Y
250
200
200
280
0
220
140
Y
0
200
200
Y
Page 13
Y
N
Object Technology Lecture 2 Notes
import objects.BankAccount;
import objects.BankCustomer;
class BankAccountLecture
{ public static void main (String args[])
{
/*
Brian, aged 18, opens a bank account without any money.
His mother, Celia aged 46, has a bank account with a balance of
£450. */
/*
Brian puts £50 into his account and then his mother transfers
£200 into her son's account. */
/*
Celia unsuccessfully tries to close her account.
Why does she fail? */
/*
Brian
Celia
Celia
Brian
checks his account's balance.
checks her account number.
then withdraws £280 from her account to pay a bill.
spends £30. */
/*
Brian then help his mother by transferring
enough money into her account to enable her to pay her bill
which she then pays. */
/*
Brian then empties his account and closes it.
Celia later puts £200 into her account and tries to repay her
son by transferring to his account the amount he lent her plus
a further £20.
*/
}
}
© De Montfort University
Page 14
Object Technology Lecture 2 Notes
Week 4 - From Use-Cases to Sequence Diagrams to Implementation (1)
Classes used - LoyaltyCard and Person, Student and Module
Learning Outcomes:
At the end of this lecture, you should be able to:
 Understand and explain the need for diagrams to represent BOTH static and dynamic views of a
model
 Read a Sequence Diagram for a use-case and understand the notation and layout and significance
of each element in the diagram
 Understand and explain the links between a Sequence Diagram, its use-case and the resulting
implementation.
Definitions and examples
Sequence Diagram
"Illustrates the behaviour specified in a use-case with the interactions shown in a time sequence."
The sequence diagrams for use-cases relating to a person obtaining a loyalty card and of a
student registering for a module are given later
Use-case
"The functionality that a system will offer from the user’s perspective”
A person must be able to take out a loyalty card, spend money to acquire points and convert
points into vouchers.
A student must be able to register for and withdraw from modules. A student must be able to
find out the number of modules on which he or she is currently registered. When registering a
student must not be able to register for more than a maximum number of modules nor be able
to register for the same module twice
Delegation
"The ability of an object to issue a message to another object, or itself, in response to a message"
When displaying itself a LoyaltyCard knows its number and points but not the details of its
owner so it delegates the display of these details to the owner, an instance of Person.
Responsibility
"An obligation that one class has to provide a service for another class"
When constructing the string containing the details of a student the toString() method requires
the details of each module on which the student in registered. It is the responsibility of the
module to provide this information. The Student toString() method delegates to the module to
supply this information.
Learning notes
Modelling the way objects dynamically interact with each other is an essential step towards
implementing a programmed solution to a problem. Sequence Diagrams simply illustrate a means of
visualising the flow of messages between Classes and or Instances / Objects over a period of time.
The Student and Module and Loyalty Card and Person classes are used to show how a Sequence
Diagram is a step between use-case and code.
The Sequence Diagrams this week are for "1 to 1"and "1 to many" associations involving 1-way
navigation only. 2-way navigation will be the subject of a later lecture.
Notes for Sequence Diagram for LoyaltyCard and Person use-cases
The following conditions restrict the number of sequence diagrams that are possible.
 Person and LoyatlyCard classes have a 1:1 association that is navigable in one direction only from
LoyaltyCard to Person.
 A Person may own zero or one LoyaltyCard. A LoyaltyCard must be associated with exactly one
person only. A LoyaltyCard therefore cannot then exist without an associated Person object.
 A Person object must be created before a LoyaltyCard object.
 A LoyaltyCard object must be created for a Person.
 A LoyaltyCard can send messages to a Person object but a Person object cannot send messages to
a LoyaltyCard object.
© De Montfort University
Page 15
Object Technology Lecture 2 Notes
Example of a Sequence Diagram
The following use-cases are represented on a sequence diagram showing object creation then some
delegation and responsibilities. The Java program below implements the solution to these use cases and
sequence diagram.
Use-cases
Sally is aged 34, she takes out a loyalty card and then spends £350. Sally checks how many vouchers
she has available on her card. She then obtains a display of her card's complete status.
The sequence diagram below follows these use-cases.
The program code implements these use-cases and sequence diagram.
application
: Person
: LoyaltyCard
Person(String, int, char)
LoyaltyCard(Person)
addPoints(int)
numberOfVouchersAvailable( )
show( )
getName( )
toString( ) self delegation
delegation
The LoyaltyCard show() method is responsible for displaying details of the state of the LoyaltyCard on the screen.
To get the card number and points it sends itself a toString() message (self delegation) to get the string to be displayed.
This toString() method cannot supply the name of the owner as this is the reponsibilty of the Person Class.
So the method delegates this to the owner by sending a getName() message to the owner (a Person object).
import objects.Person;
import objects.LoyaltyCard;
public class LoyaltyCardSequenceDiagramLecture
{
public static void main (String args[]) // makes this a program
{
Person p = new Person("Sally",34,'F');
LoyaltyCard lc = new LoyaltyCard(p);
lc.addPoints(350);
System.out.println(lc.numberOfVouchersAvailable());
lc.show();
}
}
© De Montfort University
Page 16
Object Technology Lecture 2 Notes
Notes on Sequence Diagrams for Student and Module use-cases
Student and Module classes have a 1:m association navigable from Student to Module only.
“A Student may register to study zero to eight modules.”
“A Module may be studied by zero or many students.”
The use case “register for a module” was developed and eventually implemented in code as the
method registerForModule(Module) . Before implementing this method we needed to decide what
activities must take place? Are some of these activities pre-conditions that must occur before other
activities ? Which classes have access to information or can send messages to other objects to gain
information when attempting to complete these activities. ? In general we need to assign these activities
as responsibilities to classes.
To successfully register a student on a module we need to make sure –
the student exists,
the module exists,
the student is not already enrolled on this module,
the student is enrolled on less than eight modules,
a student-module association is created.
These first four activities are called pre-conditions - "a statement of what must be true if a method is
to perform correctly".
The student exists, the module exists.
What do these first two activities mean ? What class of objects can be responsible for these checks ?
So far we have always assumed that we have direct access to the correct objects we are interested in. In
week seven we will introduce objects that will be allocated these responsibilities, at present we assume
all of these activities are undertaken by the application:Main.
The student is not already enrolled on this module.
This activity assumes that we can somehow distinguish one module from another, luckily modules
have unique codes …. To check whether one module is different from another module, one module
code will need to be compared with all the other module codes that a student is already enrolled or
registered for.
What class of object can or should be responsible for this ?
If a student has a collection of modules it is registered to study, then a student object can be responsible
for checking whether it is already enrolled on a module. The student object will need to ask each of the
modules it is registered for, for their codes. The student object will need to be sent either a module code
that uniquely identifies a module, or will need to be sent the module itself. If the student is sent a
module, the student can ask the module for its code and compare it to all of its module codes.
The student is enrolled on less than eight modules.
Again since a student has a collection of modules it is registered for, then a student object can be
responsible for knowing the number of modules it is already enrolled on. The student object can count
its number of modules.
A student-module association is created.
Student and Module classes have a 1:m association navigable from Student to Module only.
“A Student may register to zero to eight modules.”
“A Module may be studied by zero or many students.”
If we examine the class diagram for this association we can see that a module object will need to be
added to the collection of modules a student is already registered or enrolled on. We can make a
student object responsible for adding this module object to its collection of modules.
The above explanation is only one way this use case can be implemented. This design is easier to grasp
if drawn as a Sequence Diagram, or a series of Sequence Diagrams.
© De Montfort University
Page 17
Object Technology Lecture 2 Notes
_
register for a module
Application:
registerForModule(module :
Module)
: Student
: Module
hasRegisteredForModule(module : Module)
* [ index = 0 ... 8 ] getCode() ]
aCode
[if getCode != aCode]
canTakeAnotherModule( )
numberOfModules( )
[if numberOfModules < 8
]
addModule(module : Module)
The above diagram shows an optional dotted line annotated by a returning object ‘aCode’. Other
annotations are shown such as [ ] guard conditions and loops. A loop is indicated by an index variable
that is used to count the number of times a message is sent, indicated by ‘*’ and a count from zero to 8;
the maximum number of modules a student can be registered for.
Only some detail has been added to this diagram. Looping information could have been added to the
three methods canTakeAnotherModule, numberOfModules and addModule. These three methods all
deal with collections of objects.
If more detail is to be included it is perhaps better to draw four separate diagrams, one for each method.
For teaching purposes, to gain an overview of how messages are passed as responsibilities are
delegated, we often show one detailed diagram.
© De Montfort University
Page 18
Object Technology Lecture 2 Notes
Week 5 - From Use-Cases to Sequence Diagrams to Implementation (2)
Classes used - StoreCard and StoreCustomer, BankAccount and BankCustomer
Learning Outcomes:
At the end of this lecture, you should be able to:
 Read a Sequence Diagram for a use-case and understand the notation and layout and
significance of each element in the diagram
 Explain the links between a Sequence Diagram, its use-case and the resulting implementation associations
involving 2-way navigation for both "1 to 1" and "1 to many" multiplicity's.
 Explain the concept of a pre-condition
Definition and example
Pre-condition
"A statement of what must be true if a method is to perform correctly"
A StoreCustomer may have just one StoreCard. When a StoreCard is created for a
StoreCustomer that StoreCustomer must not already have a StoreCard. If this is not true then
the result of creating the StoreCard cannot be guaranteed.
Notes for Sequence Diagram for StoreCustomer and StoreCard use-cases
Constructing a StoreCard for a StoreCustomer
Although a StoreCustomer may exist without a StoreCard each StoreCard must be associated with
exactly one person. So a StoreCustomer object must be created before a StoreCard object.
The constructor for a StoreCard has a pre-condition that the owner must not already have a StoreCard.
This test must be made of the StoreCustomer before creating a StoreCard for that StoreCustomer,
because the link is in both directions each object must be linked to the other.
application
: StoreCustomer
: StoreCard
Assume that a StoreCustomer has been created
Now mak e the pre-condition check
hasCard( )
Assume that hasCard returns false
and now create the StoreCard
StoreCard(StoreCustomer)
Part of the creation of a StoreCard is
link ing the owner to the StoreCard.
This is delagted to the StoreCustomer
setCard(StoreCard)
Question
If the StoreCustomer DID already have a StoreCard and the hasCard( ) precondition was NOT tested
before creating a StoreCard for that customer what would be the state of the StoreCard and
StoreCustomer.
© De Montfort University
Page 19
Object Technology Lecture 2 Notes
Notes for Sequence Diagram for BankCustomer and BankAccount use-cases
A BankCustomer need not have an account but each BankAccount must be owned.
A BankCustomer may have a number of accounts but may not have more than a given maximum.
A program that wishes to Create a BankAccount must check the pre-condition that the BankCustomer
can open another account before attempting to create the account.
The two way links must be set at creation time.
Sequence Diagram for creating a BankAccount
application
: BankAccount
: BankCustomer
Assume that a BankCustomer has been created
Now make the pre-condition check
canOpenAnotherAccount( )
Assume that canOpenAnotherAccount returns true
and now create the BankAccount
BankAccount(BankCustomer, double)
addAccount(BankAccount)
The Customer object needs to link
itself to the BankAccount.
This is delegated to the
BankCustomer as it is the
BankCustomer's responsibility.
Crediting an Account
application
: BankAccount
credit(double)
The credit method must check
that the Bank Account can be credited
(it might be closed) and then increase
the balance. Note that
increaseBalance is a private method.
© De Montfort University
Page 20
canCredit( )
increaseBalance(double)
Object Technology Lecture 2 Notes
Sequence Diagram to represent transferring from one Account to another
Draw this sequence diagram by thinking through the use-case, then look at the actual code to see if
your design matches the one used in the code.
Notes

The methods to perform tasks such as credit, debit, transfer and close are more complex as they
involve a number of messages to perform checks.

Draw Object Diagrams to highlight the changing state and association between objects
© De Montfort University
Page 21
Object Technology Lecture 2 Notes
Week 6 - Inheritance
Learning Outcomes:
At the end of this lecture, you should be able to:
 Explain the concepts of inheritance as generalisation or specialisation
 Explain the benefits of inheritance in terms of design and code re-use
 Explain the features of inheritance as implemented in Java code.
Definitions and example
Generalisation / Specialisation
"A generalisation/specialisation relationship is one in which classes have been identified to
encapsulate common features (generalisation) or extend features (specialisation)"
generalisation - Person is a generalisation of Student, BankCustomer, StoreCustomer etc.
BankAccount is a generalisation of CurrentAccount and SavingsAccount
specialisation - StoreCard as a specialisation of LoyaltyCard
GoldCard and BonusCard are specialisations of StoreCard
CurrentAccount and SavingsAccount are specialisations of BankAccount
Inheritance
"The mechanism by which more-specific elements incorporate the structure and behaviour of moregeneral elements."
Single Inheritance
"A variation of inheritance in which a child may have only one parent"
Multiple Inheritance
"A variation of inheritance in which a child may have more than one parent"
Java supports only single inheritance and so all of the coded examples demonstrate this.
SubClass
"In a inheritance relationship this is the specialisation of another (the parent) class"
SuperClass
"In a inheritance relationship this is the generalisation of another (the child) class "
Abstract Class
"A class from which instances may not be created (typically a generalisation high in the class
hierarchy)"
Concrete Class
"A class from which instance may be created (typically a specialisation lower in the class hierarchy)"
Over-riding Method
"A method in a subclass that replaces one with the same name in a superclass"
Extending Method
"A method in a subclass that calls the one with the same name in a superclass but then carries out
additional behaviour"
© De Montfort University
Page 22
Object Technology Lecture 2 Notes
Example
A BankAccount is a generalisation of a both CurrentAccount and SavingsAccount
encompassing the common features - attributes such as balance, accountNumber and owner
and operations such as getBalance(), decreaseBalance(double anAmount).
CurrentAccount and SavingsAccount are subclasses that inherit these features and specialise
and extend with additional features - attribute overdraftLimit in CurrentAccount and operation
addInterest() in SavingsAccount.
The BankAccount class could have been made an abstract SuperClass. Objects of an abstract
class cannot be created. CurrentAccount and SavingsAccount are both concrete subclasses.
The getInterestRate() method in SavingsAccount is a new method in this sub-class.
The method canDebit(double anAmount) in CurrentAccount over-rides that in BankAccount
as it has to take into consideration the overdraftLimit feature and thus behaves differently.
The toString() method in CurrentAccount extends the toString() method in BankAccount to
return the common inherited details but then also returns the overdraftLimit.
BankAccount
(from objects)
# balance : double
# accountNumber : int
# open : boolean
# owner : BankCustomer
$ nextNumber : int = 1001
+ BankAccount(aCustomer : BankCustomer, aBalance : double)
+ BankAccount(aCustomer : BankCustomer)
+ credit(anAmount : double) : String
+ debit(anAmount : double) : String
+ transfer(anAmount : double, creditingAccount : BankAccount) : String
+ canCredit() : boolean
+ canDebit(anAmount : double) : boolean
+ isOpen() : boolean
+ isClosed() : boolean
+ canBeClosed() : boolean
+ close() : void
+ getAccountNumber() : int
+ getBalance() : double
+ getOwner() : BankCustomer
+ details() : String
+ someDetails() : String
+ displayBalance() : String
+ displayOwner() : String
+ toString() : String
+ closureDetails() : String
- increaseBalance(anAmount : double) : void
- decreaseBalance(anAmount : double) : void
SavingsAccount
(from objects)
CurrentAccount
(from objects)
- interestRate : double
- overdraftLimit : double
+ SavingsAccount(anOwner : BankCustomer, aBalance : double, anInterestRate : double)
+ SavingsAccount(anOwner : BankCustomer)
+ getinterestRate() : double
+ setInterestRate(aRate : double) : void
+ addInterest() : void
+ details() : String
+ toString() : String
+ CurrentAccount(anOwner : BankCustomer, aBalance : double, anOverdraftLimit : double)
+ CurrentAccount(anOwner : BankCustomer)
+ getOverdraftLimit() : double
+ setOverdraftLimit(aLimit : double) : void
+ canDebit(anAmount : double) : boolean
+ details() : String
+ toString() : String
© De Montfort University
Page 23
Object Technology Lecture 2 Notes
Inheritance and the Person Hierarchy
Look at the class diagram below and annotate it to explain how each subclass is a specialisation of
the class Person.
Identify new, over-riding, and extending methods and any additional attributes
Person
(from objects)
# name : String
# age : int
# gender : char
Student
(from objects)
-$ MAXMODULES : int = 8
+ Person(name : String, age : int, gender : char)
+ setName(name : String) : void
+ getName() : String
+ setAge(age : int) : void
+ getAge() : int
+ setGender(gender : char) : void
+ getGender() : char
+ toString() : String
+ show() : void
+ Student(name : String, age : int, gender : char)
- addModule(module : Module) : void
- canTakeAnotherModule() : boolean
+ registerForModule(module : Module) : void
- removeModule(module : Module) : void
+ withdrawFromModule(module : Module) : void
- numberOfModules() : int
+ getNumberOfModules() : int
+ hasRegisteredForModule(module : Module) : boolean
+ toString() : String
+ show() : void
BankCustomer
(from objects)
- accounts : BankAccount [ ]
$ MAXACCOUNTS : int = 3
+ BankCustomer(aName : String, anAge : int, aGender : char)
+ addAccount(anAccount : BankAccount) : void
+ numberOfAccounts() : int
+ numberOfOpenAccounts() : int
+ hasOpenAccounts() : boolean
+ canCloseAllAccounts() : boolean
+ closeAllAccounts() : boolean
+ canOpenAnotherAccount() : boolean
+ canOpenMoreAccounts() : String
+ hasAccount(aNumber : int) : boolean
+ getAccount(aNumber : int) : BankAccount
+ removeAccount(aNumber : int) : boolean
- removeAccount(anAccount : BankAccount) : void
+ removeAllAccounts() : boolean
- removeAccounts() : void
+ toString() : String
© De Montfort University
StoreCustomer
(from objects)
- card : StoreCard
+ StoreCustomer(name : String, age : int, gender : char)
+ setCard(card : StoreCard) : void
+ setNewCard(card : StoreCard) : void
+ getCard() : StoreCard
+ hasCard() : boolean
+ canHaveCard() : boolean
+ toString() : String
+ show() : void
Page 24
Object Technology Lecture 2 Notes
Java Code Examples
Implementing Inheritance in Java.
Annotate the following implementation of the class StoreCustomer to show evidence in the Java code
itself of inheritance.
package objects;
public class StoreCustomer extends Person
{
private StoreCard card;
public StoreCustomer(String name, int age, char gender)
{ super(name, age, gender);
card = null; }
public void setCard(StoreCard card)
{ if (this.canHaveCard())
this.card = card; }
public void setNewCard(StoreCard card)
{ this.card = card; }
public StoreCard getCard()
{ return card; }
public boolean hasCard()
{ return card != null; }
public boolean canHaveCard()
{ return card == null; }
public String toString()
{ String cardInfo;
if (this.hasCard())
cardInfo = super.toString() + " has card " + card.getCardNumber() +
" with " + card.getPoints() + " points";
else
cardInfo = super.toString() + " has no Card";
return cardInfo;
}
public void show()
{ System.out.println(this.toString()); }
}
© De Montfort University
Page 25
Object Technology Lecture 2 Notes
Inheritance and the LoyaltyCard Hierarchy
Explain all features of inheritance visible in this class hierarchy by annotating the diagram
LoyaltyCard
(from objects)
# cardNumber : int
# points : int
# owner : Person
-$ nextNumber : int = 1234
+ LoyaltyCard(owner : Person)
+ getOwner() : Person
+ getCardNumber() : int
+ addPoints(money : int) : void
+ getPoints() : int
+ takeVouchers() : int
+ numberOfVouchersAvailable() : int
+ toString() : String
+ show() : void
StoreCard
(from objects)
+ StoreCard(owner : StoreCustomer)
GoldCard
(from objects)
BonusCard
(from objects)
+ totalPoints : int
+ GoldCard(owner : StoreCustomer)
+ addPoints(money : int) : void
© De Montfort University
+ BonusCard(owner : StoreCustomer)
+ addPoints(money : int) : void
Page 26
Object Technology Lecture 2 Notes
Week 7 - Aggregation - Whole Part Association (1)
Learning Outcomes:
At the end of this lecture, you should be able to:
 Explain the concepts of aggregation
 Explain the features of aggregation as implemented in Java code.
Definitions and example
Whole-Part Associations
There are two types of whole-part associations defined as
Aggregation
"The relationship that occurs when one class is made up of many occurrences of another class.
Often described as the 'contains' relationship."
AND
Composition
"The relationship that occurs when one class is made up of several others.
Often described as the 'is-part-of' relationship"
Example
The BankCustomerBase is an aggregation of all of the Customers. The AccountBase is an
aggregation of all the BankAccounts, CurrentAccounts and SavingsAccounts. (The terms
BankCustomerBase and AccountBase are used to name the aggregations that are often
implemented as a database.) The BankCustomerBase contains Customers
The Bank is a composition of its Customers (a BankCustomerBase) and their Accounts (an
AccountBase). The BankCustomerBase is-part-of the Bank
UML provides a different notation for both Aggregation and Composition.
Aggregation (Open Diamond)
BankCustomerBase
(from objects)
Composition (Shaded Diamond and 1:1 relationship)
Bank
(from objects)
1
1
0..n
1
BankCustomer
(from objects)
-aCustomerBase
BankCustomerBase
(from objects)
Learning notes
The Bank Case Study is a complete working system but without any user interface.
Its purpose is to allow a fully designed and implemented system to be discussed in parallel with the
coursework case study.
For this lecture and the associated tutorial it allows the implementation of methods to be investigated in
detail "the lid taken off".
© De Montfort University
Page 27
Object Technology Lecture 2 Notes
import objects.BankCustomer;
import objects.BankAccount;
import objects.BankCustomerBase;
public class AggregationLecture
{ public static void main (String args[])
{ BankCustomer aCustomer1, aCustomer2; BankAccount anAccount1; BankCustomerBase aCustomerBase;
System.out.println("\nCreate an object to represent a new customer Bob \n");
aCustomer1 = new BankCustomer("Bob",45,'M');
System.out.println(aCustomer1);
System.out.println("\nCreate a bank account for Bob, with an initial balance of £50.0 \n");
System.out.println(anAccount1 = new BankAccount(aCustomer1,50));
System.out.println("\n" + aCustomer1);
System.out.println("\nCreate an object to contain some customers \n");
aCustomerBase = new BankCustomerBase();
System.out.println("The customer base contains " + aCustomerBase.numberOfCustomers() + " customers \n");
System.out.println("\nAdd Bob, Mary and Meena to the customer base \n");
aCustomerBase.addBankCustomer(aCustomer1);
aCustomerBase.addBankCustomer("Mary",36,'F');
aCustomerBase.addBankCustomer("Meena",19,'M');
System.out.println("\nThe customer base now contains " + aCustomerBase.numberOfCustomers() + " customers \n");
System.out.println(aCustomerBase.toString());
System.out.println("CustomerBase includes customer Meena = " + aCustomerBase.includesCustomerNamed("Meena")+ "\n");
System.out.println("\nTry to add a customer with the name \"Meena\" to the customer base \n");
System.out.println(aCustomerBase.addBankCustomer("Meena",19,'M'));
System.out.println("\nThe customer base still contains " + aCustomerBase.numberOfCustomers() + " customers \n");
System.out.println(aCustomerBase.toString());
}
}
© DE MONTFORT UNIVERSITY
Page 28
COMP1002 and INFO1003 Object Technology Lecture Notes
The BankAccountBase Aggregation
A collection / aggregation is responsible for adding, checking if it includes, displaying and removing
objects, knowing its size, if empty, if full, removing an object.
The BankCustomerBase acts as a 'wrapper' for, or ‘< uses >’ a java collection class (ArrayList).
The ArrayList class provides the implementation of the functionality for adding, displaying and
removing objects, knowing its size, if empty, if full, removing an object. This means that the
BankCustomerBase can use these methods by sending messages to its 'customers' attribute, an
ArrayList object.
The BankCustomerBase is responsible for adding a bank customer.
As a bank customer must be added once only, the detailed use-case will need to include a check that
the customer does not already exist in the aggregation. This part of the use-case is delegated to the
ArrayList attribute (customers). The ArrayList will need to inspect itself. This is in turn delegated to a
ListIterator that enables each element in the ArrayList to be accessed. The name of the customer object
extracted from the list is compared with the name of the customer to be added.
The following (partial) class diagram shows the classes involved
ArrayList
(from util)
BankCustomerBase
- customers : ArrayList
< uses >
1
+ ArrayList()
+ size() : int
+ isEmpty() : boolean
+ contains(elem : Object) : boolean
+ add(obj : Object) : void
+ remove(obj : Object) : boolean
+ toString() : String
+ listIterator() : ListIterator
0..*
0..n
BankCustomer
< uses >
<<Interface>>
ListIterator
(from util)
hasNext()
next()
© DE MONTFORT UNIVERSITY
Page 29
COMP1002 and INFO1003 Object Technology Lecture Notes
Use-case to 'add a new customer to a bank'. The following Sequence Diagrams show some of the
delegation involved in an implementation of this use-case.
addBankCustomerNamed (String, int, char)
: BankCustomerBase
: ArrayList
: BankCustomer
addBankCustomer(String, int, char)
includesCustomerNamed(String)
BankCustomer(String, int, char)
add(Object)
includesCustomerNamed(String)
: BankCustomerBase
: ArrayList
: ListIterator
listIterator( )
* while [ ] hasNext( )
next( )
The following Java code shows the implementation in the BankCustomerBase class. This is the
ONLY code that needs writing since we reuse the ArrayList and ListIerator classes provide by Java.
public String addBankCustomer(String aName, int anAge, char aGender)
{ if(this.includesCustomerNamed(aName))
return "Customer named " + aName + " already exists - not added";
else
customers.add(new BankCustomer(aName,anAge,aGender));
return "Bank customer " + aName + " added";
}
public boolean includesCustomerNamed(String aName)
{ BankCustomer aCustomer;
ListIterator iterator = customers.listIterator();
while(iterator.hasNext())
{
aCustomer = ((BankCustomer) iterator.next());
if(aCustomer.getName()== aName)
return true;
}
return false;
}
© DE MONTFORT UNIVERSITY
Page 30
COMP1002 and INFO1003 Object Technology Lecture Notes
Week 8 - Composition - Whole Part Association (2)
Learning Outcomes:
At the end of this lecture, you should be able to
 Explain the concepts of composition
 Explain the features of composition as implemented in Java code.
Definitions and example (a reminder)
Whole-Part Associations
There are two types of whole-part associations defined as
Aggregation
"The relationship that occurs when one class is made up of many occurrences of another class.
Often described as the 'contains' relationship."
AND
Composition
"The relationship that occurs when one class is made up of several others.
Often described as the 'is-part-of' relationship"
Example
The BankCustomerBase is an aggregation of all of the Customers. The AccountBase is an
aggregation of all the BankAccounts, CurrentAccounts and SavingsAccounts. (The terms
BankCustomerBase and AccountBase are used to name the aggregations that are often
implemented as a database.) The BankCustomerBase contains Customers
The Bank is a composition of its Customers (a BankCustomerBase) and their Accounts (an
AccountBase). The BankCustomerBase is-part-of the Bank
Aggregation (Open Diamond)
Composition (Shaded Diamond and 1:1 relationship)
Bank
(from objects)
BankCustomerBase
(from objects)
1
1
0..n
1
BankCustomer
(from objects)
-aCustomerBase
BankCustomerBase
(from objects)
Learning notes
The Bank Case Study is a complete working system but without any user interface.
Its purpose is to allow a fully designed and implemented system to be discussed in parallel with the
coursework case study.
For this lecture and the associated tutorial, the case study allows the implementation of methods to be
investigated in detail "the lid taken off".
© DE MONTFORT UNIVERSITY
Page 31
COMP1002 and INFO1003 Object Technology Lecture Notes
import objects.Bank;
public class CompositionLecture
{
public static void main (String args[])
{
Bank aBank;
aBank = new Bank();
System.out.println(aBank);
System.out.println(aBank.addBankCustomer("Heena",19,'F'));
System.out.println(aBank.addBankCustomer("Bob",45,'M'));
System.out.println(aBank.getDetailsOfCustomerNamed("Bruce"));
System.out.println("\n");
System.out.println(aBank.addNewBankAccountFor("Heena"));
System.out.println(aBank.getDetailsOfCustomerNamed("Heena"));
System.out.println(aBank.deposit(100,1004));
System.out.println(aBank.getDetailsOfAccount(1004));
System.out.println("\n");
System.out.println(aBank.getDetailsOfCustomerNamed("Mohammed"));
System.out.println(aBank.withdraw(100,1003));
System.out.println(aBank.getDetailsOfAccount(1003));
System.out.println(aBank.withdraw(100,1002));
System.out.println(aBank.getDetailsOfAccount(1002));
System.out.println("\n");
}
}
© DE MONTFORT UNIVERSITY
Page 32
COMP1002 and INFO1003 Object Technology Lecture Notes
The Bank Composition
Look at the partial class diagram below.
Read HTML for the whole bank case study and discuss possible responsibilities for the Bank Class
Bank
(from objects)
1
1
1
-anAccountBase
1
AccountBase
(from objects)
BankCustomerBase
(from objects)
1
1
0..n
0..n
BankAccount
(from objects)
SavingsAccount
(from objects)
-accounts[]
#owner
0..n owned by
1
BankCustomer
(from objects)
CurrentAccount
(from objects)
Add any attributes and operation signatures to the Bank Class below.
Bank
© DE MONTFORT UNIVERSITY
Page 33
COMP1002 and INFO1003 Object Technology Lecture Notes
Use-case - Adding a new Customer
The Bank abstraction in the case study is composed of two elements:
 its customers held as a collection of bank customers represented by a BankCustomerBase attribute
customers
 its accounts held as a collection of bank accounts represented by an AccountBase attribute
accounts
The use-cases for the Bank class include adding new customers and accounts, making transactions
(deposits, withdrawals and transfers).
We know that the BankCustomerBase class has responsibility for adding a new customer. This may be
achieved via two operations
public String addBankCustomer(String aName, int anAge, char aGender)
OR
public String addBankCustomer(BankCustomer aCustomer)
The Bank class acts as the model for the actual bank and should take overall responsibility for adding a
new customer but will delegate the actual task to the BankCustomerBase.
The Bank class (acting as an interface to the user) will simply require the new customer's name age and
gender and so will delegate its responsibility via the first of the two operations above.
We know that this method performs the necessary check to ensure that the customer does not already
exist and thus the Sequence Diagram is simple.
: Bank
: BankCustomerBase
addBankCustomer(String, int, char)
addBankCustomer(String, int, char)
See separate
Sequence Diagram
© DE MONTFORT UNIVERSITY
Page 34
COMP1002 and INFO1003 Object Technology Lecture Notes
Use-case - A Customer opens a new CurrentAccount
Consider how the Bank class can provide a method to implement this operation.
What details would need to be provided and what delegation is needed. Look at the actual
implementation of this method to confirm that your idea is correct.
Add the message signature to the class diagram
Draw the sequence diagram.
Use-case - Make a Deposit
Consider how the Bank class can provide a method to implement this operation.
What details would need to be provided and what delegation is needed. Look at the actual
implementation of this method to confirm that your idea is correct.
Does it matter what type of account is receiving the deposit?
Add the message signature to the class diagram
Draw the sequence diagram.
© DE MONTFORT UNIVERSITY
Page 35
COMP1002 and INFO1003 Object Technology Lecture Notes
Week 9 - Coursework
Learning outcomes
At the end of this lecture, you should be able to:
 Explain the requirements of the coursework assignment in terms of the deliverables and relate
these to the corresponding lectures, notes and examples used in this course.
 Explain the assessment mechanism for the coursework and the grading criteria associated
 Explain the ways in which you will receive help and guidance to complete the assignment
 Plan the order in which you will tackle to assignment
Resources
You will be provided with a separate booklet containing all details of the coursework including:
 The case study
 A UML Class diagram for the system
 The HTML documentation for all of the classes in the system
 The source code for all of the classes in the system.
 The questions to be answered
 The assessment mechanism and criteria
 The assessment sheet.
© DE MONTFORT UNIVERSITY
Page 36
COMP1002 and INFO1003 Object Technology Lecture Notes
Week 10 - Encapsulation
Learning Outcomes
At the end of this lecture, you should be able to:
 Explain the concepts of encapsulation
 Explain the features of encapsulation as implemented in Java code.
Learning notes
The Bank Case Study is a complete working system but without any user interface.
Its purpose is to allow a fully designed and implemented system to be discussed in parallel with the
coursework case study.
Definitions and example
encapsulation
"Wrapping data and operations within an object. The data stored may only be manipulated by the
operations provided."
The Bank class is composed of
(private) data - its customers and accounts
(public) operations - to manipulate the customers and accounts
The customers are held in a CustomerBase collection. The accounts are held in an
AccountBase collection.
A program wishing to modify the Bank data (the customers and accounts) may do so ONLY
via the operations provided by the Bank class.
The Bank may modify the CustomerBase ONLY via the operations provided by the
CustomerBase class.
The bank encapsulates the data customers and accounts.
The CustomerBase may modify the collection of customers it contains in an ArrayList ONLY
via the operations provided by java for the ArrayList class.
The CustomerBase class may modify a Customer ONLY via the operations provided by the
Customer class.
visibility
"Operations and attributes of a class declared as public can be accessed by all other classes,
operations and attributes declared as private can be accessed only by the class itself. To make any
private attributes visible public operations must be provided "
The balance of an account can be modified only by the methods deposit, withdraw and
transfer provided in the Bank class
Why encapsulation ?
This lecture demonstrates how attempting to manipulate data by bypassing the operations provided
may mean at best duplication of effort and misplacing responsibility and at worst incorrect results.
The following program shows how a customer may be removed from a bank without using the
operation provided.
It further shows that to make this possible one operation has to be made public when it ought to be
private.
It ultimately demonstrates the fact that this solution, that initially appears to have achieved the desired
result, does not in fact work properly.
© DE MONTFORT UNIVERSITY
Page 37
COMP1002 and INFO1003 Object Technology Lecture Notes
Tasks
1. Doing it the right way
By looking at the Java code for any of the Bank case study classes write the use-case to remove a
customer from the Bank given the customer's name. Consider all checks necessary.
Complete the Sequence Diagram on the following page for the Bank class method
removeCustomerNamed(String). Show all classes and delegation to the attributes of the
Bank.
2. Doing it the wrong way
Read the Java program given in later pages and draw an Object Diagram for the objects used to show
why the solution does not work correctly.
Discussion
1. Doing it the right way
The removal of a customer from the bank is handled by a method in the Bank class
removeCustomerNamed(String aName) which performs all of the necessary checking of any preconditions namely checking that the customer can be removed.
This pre-condition is delegated to the CustomerBase via the method canRemove(BankCustomer
aCustomer) as is the actual removal of the customer via the method
removeCustomer(BankCustomer aCustomer).
This removeCustomer method delegates the removal of the accounts to a method of the Customer class
removeAllAccounts(). Accounts may be removed from and by the customer but NOT from the
AccountBase in the Bank.
The Bank then delegates to the AccountBase the responsibility of removing all the customer's accounts
via the method removeAllAccountsOf(aCustomer). In this way the 2-way link between
Customer and Account is removed.
2.
Doing it the wrong way
The removal of a customer is handled by a program which bypasses all of the bank methods and
directly accesses the CustomerBase which requires access to a method remove(aCustomer).
This method was made public here to demonstrate this teaching point but should be private. It is
not designed to be responsible for making the check that the customer has no accounts - it simply
removes a customer without checking.
For the scenario where a customer has accounts this program removes neither the accounts from
the customers collection of accounts nor the accounts from the AccountBase and the 2-way link is
not broken.
Association and navigability
For both of the above refer to class and object diagrams for the Bank case study that show
aggregation association
a customer base CONTAINS customer objects
TWO WAY link association
between a customer and an account
responsibility
a customer base is responsible for removing a customer
delegation
a customer is responsible for removing an account from its collection of accounts
an account base is responsible for removing account objects
© DE MONTFORT UNIVERSITY
Page 38
COMP1002 and INFO1003 Object Technology Lecture Notes
To be completed
: Bank
© DE MONTFORT UNIVERSITY
: BankCustomerBase
Page 39
: AccountBase
COMP1002 and INFO1003 Object Technology Lecture Notes
import objects.Bank;
import objects.BankCustomer;
import objects.BankCustomerBase;
public class EncapsulationLecture
{
public static void main (String args[])
{
Bank aBank;
BankCustomer aCustomer, aCustomer2;
BankCustomerBase aCustomerBase;
//
aBank = new Bank();
System.out.println(aBank);
//
show that account 1003 is owned by "Mohammed"
System.out.println("Display account with AccountNumber 1003\"\n");
System.out.println(aBank.getAccountNumber(1003));
//
assign to a variable an object representing a customer named "Mohammed" who owns account 1003
System.out.println("\nStore in aCustomer the customer named Mohammed");
aCustomer = aBank.getCustomerNamed("Mohammed");
System.out.println(aCustomer);
//
assign to a variable a customer base, show that "Mohammed" is in the customer base
System.out.println("\nStore in aCustomerBase the customers collection");
aCustomerBase = aBank.getCustomers();
System.out.println(aCustomerBase);
//
send a message to a customer base to remove a customer object
System.out.println("\nNow remove the customer named Mohammed stored in aCustomer");
aCustomerBase.remove(aCustomer);
© DE MONTFORT UNIVERSITY
Page 40
COMP1002 and INFO1003 Object Technology Lecture Notes
//
show that "Mohammed" has been removed from the customer base
System.out.println("\nDisplay the customers held in the variable aCustomerBase");
System.out.println(aCustomerBase.toString());
//
show that "Mohammed" has been removed from the bank
System.out.println("\nNOW - Attempt to display the details of the customer named Mohammed");
System.out.println(aBank.getDetailsOfCustomerNamed("Mohammed"));
//
show that account 1003 is STILL owned by Mohammed
System.out.println("\nBUT we can still get the account numbered 1003!!!!!!");
System.out.println(aBank.getAccountNumber(1003));
//
//
//
show that a customer named "Mohammed" has not been removed from the bank
assign to a variable the customer who owns account 1003
show "Mohammed" is not removed, only a LINK association was removed
System.out.println("\nAND we can get the owner of account 1003 - who is Mohammed !!!!!");
aCustomer2 = aBank.getAccountNumber(1003).getOwner();
System.out.println(aCustomer2);
//
System.out.println(aBank);
}
}
© DE MONTFORT UNIVERSITY
Page 41
COMP1002 and INFO1003 Object Technology Lecture Notes
Week 11 & Week 12 - Coursework
© DE MONTFORT UNIVERSITY
Page 42
Download