Object Technology Lecture 1 Notes Contents Objects, Messages and Classes ............................................................................................................. 2 Learning Outcomes .......................................................................................................................... 2 Discussion ........................................................................................................................................ 2 Objects ....................................................................................................................................... 2 Class ........................................................................................................................................... 5 Class Diagrams........................................................................................................................... 5 Interface ..................................................................................................................................... 7 Use case, class responsibility and association ...................................................................................... 8 Learning Outcomes .......................................................................................................................... 8 Case Study - University Accommodation Agency - background details. ................................. 8 Use case diagram...................................................................................................................... 10 Discussion ...................................................................................................................................... 11 Use Case - statement development ........................................................................................... 11 use case 'register a new student' ............................................................................................... 11 use case 'create a new tenancy' ................................................................................................. 15 use case 'contact a student in hall' ............................................................................................ 16 Sequence Diagrams ............................................................................................................................ 17 Learning Outcomes ........................................................................................................................ 17 Discussion ...................................................................................................................................... 17 use case 'change a student's name' ............................................................................................ 17 use case 'display a student's details' .......................................................................................... 18 use case 'display a student's details' .......................................................................................... 19 Association, navigation and multiplicity ............................................................................................ 24 Learning Outcomes ........................................................................................................................ 24 Discussion ...................................................................................................................................... 24 multiplicity ............................................................................................................................... 25 use case 'display a room and its details' .................................................................................... 27 use case 'create a new tenancy agreement' ............................................................................... 29 Generalisation concepts and inheritance ............................................................................................ 30 Learning Outcomes ........................................................................................................................ 30 Discussion ...................................................................................................................................... 30 use case 'create a new tenancy agreement' ............................................................................... 30 Aggregation and Composition ............................................................................................................ 47 Learning Outcomes ........................................................................................................................ 47 Discussion ...................................................................................................................................... 47 Aggregation - (contains)........................................................................................................... 53 Composition a special form of aggregation.............................................................................. 56 Class Responsibility and Collaboration (CRC cards) ......................................................................... 57 Learning Outcomes ........................................................................................................................ 57 Discussion ...................................................................................................................................... 57 use case 'add a new customer to the bank' ................................................................................ 60 Development of a conceptual model .................................................................................................. 63 Learning Outcomes ........................................................................................................................ 63 Discussion ...................................................................................................................................... 63 use case 'create a new tenancy agreement' ............................................................................... 63 Use case driven design ....................................................................................................................... 69 Learning Outcomes ........................................................................................................................ 69 Discussion ...................................................................................................................................... 69 use case 'register a student for a module' .................................................................................. 69 Allocating responsibilities ........................................................................................................ 69 use case 're-register a student for a module' ............................................................................. 75 use case 'record a grade for a student' ...................................................................................... 76 factors to be considered in design ............................................................................................ 77 Definitions and examples ................................................................................................................... 78 © De Montfort University Page 1 Object Technology Lecture 1 Notes Objects, Messages and Classes Learning Resources UML Object / Class diagrams, definitions and conventions chalk / whiteboard Pens - for definitions, diagrams etc. Learning Outcomes Students should: be able to understand and appropriately use within the context of 'Object Technology' and 'UML' the terms modelling, behaviour, class, object, attribute, state, operation, message for a simple model draw a UML object diagram with identity, attributes and state for a simple model draw a UML class diagram with a class name, attributes and operations show how both instances and classes can respond to messages that are part of their common, interface. To understand that a message may result in no change of state, a change of state, a different outcome dependant on the state of an instance, or an error. Discussion Objects "an object is a thing you can interact with: you can send it various messages and it will react. How it behaves depends on the current internal state of the object, which may change, for example as part of the object's reaction to receiving a message. It matters which object you react with , you usually address an object by name; that is, an object has an identity which distinguishes it from all other objects." [Grady Booch] myKitchenClock myAlarmClock anotherClock These pictures are called ‘object diagrams’. All objects have an identity (a name), myKitchenClock, myAlarmClock, anotherClock, The identity is written at the top of the diagram and underlined. We, as designers, choose the identity for our objects. We could have chosen a,b,c instead but this would make our diagrams difficult for anyone else to read so we always try to give our objects meaningful identities. Sometimes, this means that we want to use more than one word in an identity e.g. my kitchen clock. Most programming languages don’t allow spaces in identities, so we use the convention of upper-case character for second and subsequent words. The object diagrams should also include some details about our clocks but we only include (model) those attributes and behaviour we are interested in. We could be only interested in the fact that “all clocks have a timing mechanism”. It is the timing mechanism that actually stores the current time. © De Montfort University Page 2 Object Technology Lecture 1 Notes These timing mechanisms can also be modelled as objects. We can draw object diagrams to represent these timingMechanisms … anElectronicTM aSundialTM aClockworkTM AnElectronicTM, aClockworkTM, aSundialTM are all ‘timingMechanism’ objects, they have common features such as the ability to calculate and store the current time. We can show the association between a clock objects and a timingMechanism object - myKitchenClock anElectronicTM myAlarmClock aSundialTM anotherClock aClockworkTM we have modelled ‘clock’ and ‘timingMechanism’ as two separate but related objects an advantage of modeling a timingMechanism as separate from a clock is that we could easily change a timingMechanism eg. a sundial may not be the most reliable timing mechanism for an alarm clock myAlarmClock, myKitchenClock, anotherClock are all ‘clock’ objects, they have common features such as a timingMechanism’, we say that a timingMechanism is an attribute of a clock object all clock objects have this attribute but the actual timingMechanism can be different, we say that a clock’s timingMechanism attribute may have different states all timingMechanism objects store the current time, so they must have a currentTime attribute © De Montfort University Page 3 Object Technology Lecture 1 Notes The currentTime of a timingMechanism will be implemented as a very large number Note that the currentTime of our timingMechanisms is different, we say that each of these objects has a different state anElectronicTM aSundialTM aClockworkTM currentTime = 123456789 currentTime = 134567892 currentTime = 135678924 the clock objects have other features such as the ability to set and display the time, all clock objects share these behaviours and have methods to implement the required behaviour. So all clock objects can perform common operations when we want an object to implement an operation we say that we send a message to that object. Objects that share common operations can respond to common messages eg. we can set the time of a clock we have to manually set the time on some clocks (move the hands or press hour/minute/seconds buttons etc). Some clocks are controlled by computer and we can type the new time in at the keyboard. The idea of sending a clock object a message to tell it to set its time is abstract but is still a good example of some fundamental OT concepts <receiver> <message> <return> myKitchenClock setTime(“12.30”) void But it is myKitchenClock’s timingMechanism that actually stores the current time (and remember this is stored as a large whole number) – we do not communicate directly with the timingMechanism (we probably don’t know what this number is), instead we let myKitchenClock take responsibility for setting the new time but myKitchen clock will actually delegate this task to its timingMechanism <receiver> <message> <return> anElectronicTM setTime(“12.30”) void Which object has the responsibility of converting “12.30” into the large number ? © De Montfort University Page 4 Object Technology Lecture 1 Notes <receiver> <message> <return> anElectronicTM setTime(1257896) void Which object now has the responsibility of converting “12.30” into the large number ? What does “void” mean? Clearly, the designer must decide what responsibilities each object in the system will have. In order for a myKitchenClock to display the time, it must get the current time from anElectronicTM – so its sends anElectronicTM a message. <receiver> <message> <return> anElectronicTM getTime() 140765321 Which object has the responsibility of converting 140765321 into an hour/minute format for display? How do we know what messages an object can respond to ? Class Objects of a similar type can be classified by common behaviour, the class of an object specifies common operations that can be applied by these objects, all objects of the same class can understand the same messages. Designers decide what classes are needed in a system and what attributes and operations each class should incorporate. Class Diagrams As a UML Class diagram we can represent a simple TimingMechanism as - TimingMechanism class name currentTime attribute getTime setTime stop start indicative behaviour or operations © De Montfort University Page 5 Object Technology Lecture 1 Notes Time is the valid range of all states of time. : Time : void aTime : Time aTime indicates that this operation returns a value of the type Time. indicates that the operation does not return any value. indicates that the parameter aTime is of the type Time. is a value, a very large positive number as defined by Time. TimingMechanism currentTime : Time getTime( ) setTime(aTime : Time) stop( ) start ( ) : Time : void : void : void The getTime operation returns a very large number from the timingMechanism attribute of the Timepiece, displayTime uses this very large Time number and converts it to a form that we recognise as hours, minutes and perhaps seconds … called a String Clock - timingMechanism : TimingMechanism - getHours( ) - getMinutes( ) + setTime(aString : String) + stop( ) + start ( ) + displayTime( ) : int : int : void : void : void : String Clock has a public interface, this shows the public operations available to users of the class © De Montfort University Page 6 Object Technology Lecture 1 Notes Interface If you want to use aClock you are not interested and cannot see the timingMechanism or the internal private representation of the state of the object. A user of an object of a class is only interested in the messages that the object understands - that provide services to the user. There are no attributes or private operations included in an interface - <<interface>> Clock setTime(aString : String) stop( ) start ( ) displayTime( ) : void : void : void : String A class diagram representing a model of a timepiece and its associated timing mechanism, Time and String class diagrams could also be included. Clock TimingMechanism - timingMechanism : TimingMechanism - currentTime : Time - getHours( ) - getMinutes( ) + setTime(aString : String) + stop( ) + start ( ) + displayTime( ) : int : int : void : void : void : String © De Montfort University + getTime( ) + setTime(aTime : Time) + stop( ) + start ( ) Page 7 : Time : void : void : void Object Technology Lecture 1 Notes Use case, class responsibility and association Learning Resources UML use case and class diagram examples, notes on association, multiplicity, navigation. 'Student Accommodation ' case study example or similar Learning Outcomes Students should be able to: from a simple problem statement identify the actors, a series of use cases and some of the system's requirements for a series of use cases draw a UML use case diagram, adding actors, use cases and associations develop some use cases as statements and draw UML class diagrams, adding attributes, operations / responsibilities and navigation Case Study - University Accommodation Agency - background details. The university runs an accommodation agency to provide accommodation for many of its students. The university offers some places in Halls of Residence, in single rooms only. Information is kept about privately owned rented accommodation such as flats and houses. The agency would like a computer system to monitor how much and which hall accommodation remains vacant. The existing system is paper-based The new system will be computerised What must the new system do? 1. The new system will enable students to efficiently find suitable, available accommodation. There are two types of accommodation: a) University halls of residence b) Private landlords 2. The new system will process the tenancy agreements between the student and the university for halls of residence tenancies Students are allowed to make only one current tenancy agreement. A tenancy contract is not ended until all outstanding rent is paid. 3. The new system will record the name, address of private landlords. It will NOT process tenancy agreements between students and private landlords © De Montfort University Page 8 Object Technology Lecture 1 Notes Problem Statement - Student Accommodation Agency. Brief Report The university runs an accommodation agency to provide accommodation for many of its students. The university offers some places in Halls of Residence, in single rooms only. Information is kept about privately owned rented accommodation such as flats and houses. The agency would like a computer system to monitor how much and which hall accommodation remains vacant. Interviews Karen has been accepted on a course at a university. Karen would like a place in 'hall' for her first year. She enquires at the university's accommodation agency for information about local, cheap rooms. Trevor is busy in September registering new students and adding rooms to lists of files in the agency. Bill is a good student, now in his second year. Bill last year had to work part time to pay for his rent and still got into arrears. He would like to live in hall again but he cannot until he has paid his rent. So Bill has worked through the summer at the agency ! © De Montfort University Page 9 Object Technology Lecture 1 Notes Who are the possible users / actors of the Student Accommodation System ? Karen is an instance of a Student, Trevor is an instance of agency personnel. Bill plays the role of aStudent, aDebtorStudent and agencyPersonnel. Actors Student Parent Mentor Landlord University Accommodation Agency personnel Students use the system to find out about availability, location, price, deposits, check rents (termly, in advance, direct debits…) start a new tenancy make rent payments end a tenancy The University Accommodation Agency wants : access to all accommodation registered with the agency access to all students using the agency access to all tenancy agreements to determine if a student is in arrears / owes rent the ability to add / remove students / accommodation the ability to make a new tenancy agreement ... Use case diagram Definition of a use case diagram “the functionality that the system will offer from the user’s perspective” add a new room register a new student WWW enquire about rooms debtorStudent pay rent C lerk create a new tenancy Student report student in debt © De Montfort University Page 10 Object Technology Lecture 1 Notes Discussion Use Case - statement development deliverables from the analysis phase of development is the identification of some functional systems requirements knowledge of the users of the system some use cases use cases are developed as a narrative to become a 'set of sequences of actions, including variants', to enable us to discover abstractions (types / classes) within the problem domain use case 'register a new student' A. Study the current manual system to ‘register a new student ’. Actor (student) / Action Response (Clerk) 1 - student asks to be put on file 3 - student completes registration form 2 - check to see if already on file 4 - checks form and creates a student record 5 - add record to filing cabinet B. Analyse the current system in general, abstract out essential actions from the existing processes NOTE - After discussion ‘we’ decide that a student may appear only once on the system. (WHY?) Actor / Action Response (Clerk) 1 - request to be added to the system 3 - provide confirmation 5 - details to add 2 - confirm eligible to be added 4 - check if already added 6 - create record 7 - add record to system 8 - confirm successful addition Enter student details What details ?? Name, Course ..... What will be seen on the screen ?? Menu, Dialog box, list of names ...... Check to see if student is on the system already What happens if they are ? Warning given, re-enter new details,.... What happens if they are not ? Add student, confirmation given,.... C. Design the use case statement for a computer system Actor (agency officer) Action System Response 1 - type in password 3 - select add student 5 - enter student name 7 - enter remaining details 2 - present menu / windows 4 - prompt for student name 6 - check for duplicate 8 - create new student (object) , allocate registration number 9 - add student 10 - display confirmation NOTE - The registration number will uniquely identify the student with the accommodation agency. © De Montfort University Page 11 Object Technology Lecture 1 Notes aStudentA number name aStudentB = 1001 = "Dave" number name aStudentC number name = 1235 = "Karen" = 1002 = "Dave" aStudentD number name = 6789 = "William" The above diagrams are simple object diagrams – showing the attributes and state of four representations of objects in our system. We can classify objects by their similarity. We do not classify objects by the similarity of their attributes or data. We classify objects based on the similarity of their behaviour. Obviously all students are similar – they have names and numbers, different numbers but sometimes the same or similar names. This is not so important. Importantly similar objects can undertake the same behaviour. All of our students can be registered with the accommodation agency, they can enquire about halls, can participate in a tenancy agreement, become rent defaulters etc. So we can group or classify objects by their behaviour – we call this classification a class. An object diagram shows the state or value of objects, they do not all have the same names. One class diagram will show the possible behaviour of all similar classed objects. We need one class diagram but many object diagrams. class name – by convention starts with an upper case letter Student number name attributes or data register makeTenancyAgreement payRent toString operations / behaviours aStudentA : Student aStudentB: Student number = 1001 name = "Dave" number = 1002 name = "Dave" aStudentC : Student aStudentD : Student number = 1235 name = "Karen" © De Montfort University number = 6789 name = "William" Page 12 Object Technology Lecture 1 Notes - number - name : int : String A class diagram can be used to show design decisions, such as the visibility of attributes and operations, the ‘type’ of this data or what an operation returns. + getNumber( ) + getName( ) + setName(aName : String) + toString( ) : int : String : void : String Often attributes are ‘private’ indicated by ‘-‘ this means that if another object wants to know the name of a Student object then this will only be achieved by sending a ‘public’ message indicated by ‘+’ Student aStudent.getName(); Typically class diagrams show attributes as private and operations as public. Each attribute will often have two operations associated with it. A ‘getter’ and a ‘setter’ or modifier. All objects are responsible for ‘displaying’ themselves, their details. In java this is achieved by a ‘toString’ operation. In the diagram above ‘number’ does not have a set operation since this is a unique number that cannot be changed. Questions to be answered are :Who or what is responsible for creating the instances / objects of student ? Where does the value of 'number' come from ? The class of an object is responsible for creating objects of the class. This is called instance creation or 'instantiation'. The operation that is responsible for this behaviour is called a class constructor. aStudent = new Student("Harjinder"); System.out.println(aStudent.toString()); © De Montfort University Page 13 <screen output> Harjinder, student number 1003 Object Technology Lecture 1 Notes The registration number will uniquely identify the student with the accommodation agency. Every student object has a different number and does not need to know or be responsible for the numbers of other student objects. So we can give the responsibility of knowing or remembering the last unique number to the class Student, this number can be used to give the next unique number to the next new student object … Student - number $ nextNumber - name : int : int : String + getNumber( ) + getName( ) + setName(aName : String) + toString( ) Student(aName : String) : int : String : void : String : Student A class attribute or variable can be indicated by the dollar symbol ‘$’, underlining the attribute or by using both conventions at the same time. Frequently this is called a static attribute. A class or static attribute / operation has class scope. To access a class attribute you need to access the class not the object. Typically code such as :System.out.println(Student.nextNumber) will display the next number of the Student class, to be used when creating a new student object. <screen output> 1004 aStudent.nextNumber Student.nextNumber returns an error message to a class A simple class constructor method responsible for creating a new student object with the next unique number would typically be coded in java as :- public Student(String aName) { number = nextNumber++; name = aName; } © De Montfort University Page 14 Object Technology Lecture 1 Notes If the student record already exists - the registration will be unsuccessful. Variant of the use case ‘register a new student ’. Actor (agency officer) Action System Response 1 - type in password 3 - select add student 5 - enter student name 2 - present menu / windows 4 - prompt for student name 6 - check for duplicate 7 - display failure - student exists NOTE - The student name will not uniquely identify a student, there will be many ‘Smiths’, ‘Patels’ etc. typically in this type of system a list of all Smiths will be displayed – along with course and other details like home address – to be used in checking if a particular student is already on the system. use case 'create a new tenancy' Study the current manual system to 'create a new tenancy', analyse the current system in general, abstract out essential actions from the existing processes, design the use case statement for a computer system. Actor (agency officer) Action System Response 1 - type in password 3 - select new tenancy 5 - enter student identifier 2 - present menu / windows 4 - prompt for student name or number 6 - check if student is on the system 7 - check not currently renting (not owing rent) 9 - check if available to rent (not currently being rented) 10 - add payment details 11 - rent room to student 12 - display confirmation - tenancy created 8 - enter room unique identifier For this simple version of the accommodation agency - the storing of payments details is ignored assume it is part of a different system , perhaps paper based ? Karen has rented a hall room - " room number 12 at New Lodge hall " aStudent : Student number name aRoom : Room = 1235 = "Karen" number hall = 12 = "New Lodge" " a student rents zero or one room, a room is rented by zero or one student" © De Montfort University Page 15 Object Technology Lecture 1 Notes use case 'contact a student in hall' For the use case 'contact a student in hall' - we know the student's name is "Karen", how do we find her address in hall, so we can print an address label ? aStudent.getName() == "Karen"; to find the object representing a student with a name … Student # 1235 Karen is renting 12 New Lodge Student # 6789 Bill is not renting aStudent.toString() - must display a student's details + details of the room she is renting, we need to add an extra attribute 'room', we do not link the student object to a room by a room number. aStudent : Student number name room aRoom : Room = 1235 = "Karen" = aRoom number hall = 12 = "New Lodge" toString() method of Student, no association to Room /** Returns a String describing a student … */ public String toString() { String details; details = "Student # " + number + '\n' + name; return details; } toString() method of Student, now Student is associated to Room /** Returns a string describing a student … */ public String toString() { String rentingDetails; rentingDetails = "Student # " + number + '\n' + name; if (room == null) return rentingDetails += "is not renting a room"; else return rentingDetails += " is renting " + room.toString(); } The above code assumes that Room has a method toString(), this design is better than using getNumber() and getHall() in the Student toString() method to get the number and hall details of a room. Student has less knowledge of the internal representation of Room. If Room(s) have new details this will require a change to the Room toString() method, but the toString() method in Student will not need to be changed. © De Montfort University Page 16 Object Technology Lecture 1 Notes Sequence Diagrams Learning Resources notes on UML use case statements, object and class diagram, sequence diagrams. 'Student Accommodation' case study example or similar Learning Outcomes Students should be able to: read a sequence diagram for simple use case statements and a related class diagram develop and draw a sequence diagram for simple use case statements and a related class diagram Discussion use case 'change a student's name' Student # 6789 William Student # 6789 Bill Develop the use case 'change a student's name' change the state of the attribute name from William to Bill aStudent : Student number = name = 6789 William aStudent : Student number = name = 6789 Bill aStudent object has been modelled and made responsible for knowing its number and name, aStudent has operations to get, set and can display its number and name. << Interface>> Student Student - number nextNumber - name : int : int : String + getNumber( ) + getName( ) + setName(aName : String) + toString( ) Student(aName : String) : int : String : void : String : Student getNumber( ) getName( ) setName(aName : String) toString( ) : int : String : void : String To understand what services an object can provide / what messages an object can understand we must examine the public interface of the object. © De Montfort University Page 17 Object Technology Lecture 1 Notes A sequence diagram showing the message passing of the use case 'change a student's name' . aStudent: Student time getName() use case notes confirm the name of 'a student' is "William" change the name of this student to "Bill" confirm the name of 'a student' is " Bill " "William" object setName("Bill") lifeline {name = "Bill"} active line void / nothing getName() message optional return "Bill" © De Montfort University Page 18 Object Technology Lecture 1 Notes use case 'display a student's details' Develop the use case 'display a student's details' - Student # 6789 Bill is not renting a room Student # 1235 Kate is renting 12 New Lodge This use case involves dynamic behaviour - activities / events. This is not easily represented by a class diagram. A class diagram describes static behaviour. The object diagram below shows that if a student is renting a room, then there must be an association between aStudent and aRoom. aStudent : Student number name room aRoom : Room = 1235 = " Kate" = aRoom number hall = 12 = "New Lodge" aStudent : Student number name room = 6789 = "Bill" = null To understand what messages can be sent to aStudent object to display its details, we look at the public interface of student. <<interface>> aStudent.toString(); Student Describe the use case 'display a student's details' as a set of sequences of actions, including variants. getNumber( ) getName( ) setName(aName : String) toString( ) : int : String : void : String aStudent object has been modelled and made responsible for knowing its number and name, so aStudent can display its number and name. aStudent object can be modelled and made responsible for knowing if it is renting a room. It is not responsible for knowing the details of the room, students can delegate the responsibility of displaying the details of the room they rent, to the room. If aStudent is not renting a room display the message "is not renting a room" else display the message "is renting " © De Montfort University Page 19 Object Technology Lecture 1 Notes The above object diagram shows an association between a student and a room. We want to model a student delegating the responsibility of displaying room details to a room. We can show these design decisions on a class and sequence diagram - Student aStudent can send a message to aRoom to display itself. - number - name - room : int : String : Room + getNumber( ) + getName( ) + setName(aName : String) + toString( ) : int : String : void : String :main aStudent: Student aRoom: Room toString() a student is responsible for displaying its number and name, responsibility for displaying details of any room being rented is delegated to the room toString() toString() a student is responsible for displaying its number and name, [room != "null"] toString() a student is responsible for knowing if it is renting a room dotted returns are 'optional' - returns are not needed if active double lines are drawn square brackets indicate a [guard condition] a guarded condition only 'fires' if true the condition equates to true © De Montfort University Page 20 Object Technology Lecture 1 Notes Student public Boolean isRenting() { return room != null; } - number - name - room : int : String : Room + getNumber( ) + getName( ) + setName(aName : String) + toString( ) + isRenting() : int : String : void : String : Boolean aStudent : Student :main toString() isRenting() one possible scenario variant of the use case 'display a students details' - is renting [isRenting =="true"] toString() [ isRenting ] square brackets guard condition toString() isRenting() another possible scenario variant of the use case 'display students details' is not renting © De Montfort University [isRenting == "false"] Page 21 aRoom : Room Object Technology Lecture 1 Notes aStudent : Student aRoom : Room :main toString() isRenting() a student is responsible for displaying its number and name, toString() a student is responsible for knowing if it is renting a room /** Returns a String describing a student … */ public String toString() { String rentingDetails; rentingDetails = "Student # " + number + '\n' + name; if (! this.isRenting() ) return rentingDetails += " is not renting a room"; else return rentingDetails += " is renting " + room.toString(); } © De Montfort University Page 22 Object Technology Lecture 1 Notes aStudent: Student aRoom: Room :main 1: toString() 2: isRenting() [isRenting == "true"] Conditional behaviour. The sequence diagram shows all scenario / variants of the use case. 3: toString() 3: [isRenting == "false"] This is correct UML notation but at times it is too difficult to read. The preferred diagram shows only one scenario variant. © De Montfort University Page 23 Object Technology Lecture 1 Notes Association, navigation and multiplicity Learning Resources UML use cases statements, object and class diagram examples, notes on sequence diagrams 'Student Accommodation' case study example or similar Learning Outcomes Students should be able to: understand the UML notation and concepts used in class and sequence diagrams for multiplicity, the implementation of associations, use cases and navigation for simple use case statements involving the need for association and navigation between classes develop and draw appropriate class and sequence diagrams Discussion The Unified Modelling Language as a 'language' is a means of communication. It is important that a UML diagram has the same meaning to everyone. Class diagrams will frequently show relationships between different classes. The most common relationship is a simple association. This will be drawn as a line between classes. This line will often be annotated with figures denoting multiplicity and words referring to the role a class plays in an association. Multiplicity indicates how many objects of the class may participate in an association. Figures include 0,1,2, … n, *. The star or asterisk '*' symbol indicates 'many'. On its own this can mean zero, one or many. A UML diagram showing an association as 0 ... * is the same as * . The symbol 'n' indicates that the number of objects in an association are limited, but as yet are unknown. Frequently '*' and 'n' are used implying many. A line indicating association may include an arrow in none, one or both directions. This indicates the ability to navigate from one class of objects to another. Navigation is the ability to send messages from one class of object to another. A line of association with no arrow implies that either no decision has yet been made about the direction of navigation or that navigation is possible in both ways. Navigation decisions are made at the design stage of modelling. A line of association with one arrow means messages can be sent from objects of the class with no arrow head to objects of the class pointed to by the arrow. Navigation can also be indicated by an attribute of one class being placed in another class or by annotating a model with rolenames. As use cases are developed as a series of statements, responsibilities are distributed to participating classes. These statements will require messages to be sent from one class of object to another. Decisions can then be made about the need for navigation. © De Montfort University Page 24 Object Technology Lecture 1 Notes multiplicity class notation - simple associations Lecturer 0..1 teaches 0..1 Student a lecturer teaches zero or one student a student is taught by zero or one lecturer Lecturer 0..1 teaches 1 Student a lecturer teaches exactly one student a student is taught by zero or one lecturer Lecturer 1 teaches 1 Student a lecturer teaches exactly one student a student is taught by exactly one lecturer Lecturer 0..1 teaches * Student a lecturer teaches zero one or many students a student is taught by zero or one lecturer Lecturer 0..1 teaches 1..* Student a lecturer teaches one or many students a student is taught by zero or one lecturer Lecturer * teaches * Student a lecturer teaches zero one or many students a student is taught by zero, one or many lecturers © De Montfort University Page 25 Object Technology Lecture 1 Notes For the use case "display a student's details" a student delegates the display of a room's details by sending a message to room. A Student has an attribute room : Room Student number name room : int : String : Room toString() : String Room 0..1 rents 0..1 room number hall : int : String toString() : String Multiplicity should be read as " a student rents zero or one room, a room is rented by zero or one student " This navigation from Student to Room is shown by the arrow head, the 'room : Room' attribute in Student and the annotation of the association with the rolename 'room'. In the UML only one of these indicators of navigation is needed. For the use case 'display a room and its details including possible tenants', a room needs to delegate the responsibility of displaying tenant details by sending a message to its tenant. Room will require an attribute tenant : Student . Student number name : int : String toString() : String Room 0..1 tenant rents 0..1 number hall tenant : int : String : Student toString() : String Multiplicity should be read as " a (student) tenant rents zero or one room a room is rented by zero or one student " A room knows about its tenant. A room can navigate from itself to Student; note the direction of the arrow. How do we interpret the diagram below ? Student number name room : int : String : Room toString() : String © De Montfort University Room 0..1 tenant rents Page 26 0..1 room number hall tenant : int : String : Student toString() : String Object Technology Lecture 1 Notes use case 'display a room and its details' Room is responsible for displaying its own details and will delegate the display of a tenants' details to the tenant. If the room is not currently available Room will send the message tenant.toString() . If the room is available then the 'tenant' attribute will not be set, it will be null. Any message sent to null will produce an error. Room needs to check if it is available before sending the toString() message. Rather than the class directly testing whether the private tenant attribute is null, this test can be wrapped in an operation 'isAvailable()'. This has the advantage that as a public operation it can be used by users of objects of this class to see if a room is available for rent. This will be needed by the use case involving renting a room to a tenant. A room can only be rented to one student at the same time. Within the toString() operation of Room, Room delegates to itself the responsibility of knowing whether a room is available for renting. This is called 'self delegation'. This simply means that Room sends itself a message to enquire whether it is available for rent. A Boolean is returned - true or false. use case 'display a room and its details' - described as "a set of sequences of actions, including variants" 1. aRoom is responsible for knowing its number and hall, aRoom can display its number and hall 2. aRoom is responsible for knowing if it is available for rent a room is not responsible for knowing the details of its tenants, 3. aRoom delegates the display of a student's details to the student if the room is not currently being rented display a message "is available to rent" else display the message "is rented by " 4. aStudent is responsible for knowing its number and name, aStudent can display its number and name Room - number - hall - tenant : int : String : Student + getNumber( ) + getHall( ) + setHall(aDescription : String) + toString( ) + isAvailable() + toString() : int : String : void : String : Boolean : String © De Montfort University Page 27 Object Technology Lecture 1 Notes aRoom: Room aStudent: Student :main 1: toString() 2:isAvailable() [isAvailable == "false"] conditional behaviour scenario / variants of the use case 'display a room and its details' 3: toString() [isAvailable == "true"] aStudent : Student number name room aRoom : Room = 1235 = "Karen" = aRoom number address tenant /** Returns a String describing a room … */ public String toString() { String roomDetails; roomDetails = "Room # " + number + '\n' + = 12 = " New Lodge " = aStudent hall; if ( this.isAvailable() ) return roomDetails += " is available for rent"; else return roomDetails += " is rented by " + tenant.toString(); } © De Montfort University Page 28 Object Technology Lecture 1 Notes use case 'create a new tenancy agreement' rent a room to a student - (assume the students is already ‘on’ the system ) Actor (agency officer) Action System Response 1 - type in a password 3 - select create new tenancy 5 - enter student number 2 - present menu / windows 4 - prompt for student number 6 - check if student is on the system 7 - check is eligible to rent (not renting, no rent arrears) 9 - check room is available to rent (not currently rented) 10 - add payment details 11 - rent room to student 12 - display confirmation - tenancy created 8 - enter room unique identifier aStudent : Student number name room aRoom : Room = 1235 = "Karen" = aRoom number hall tenant Student = 12 = "New Lodge" = aStudent Room - number nextNumber - name - room : int : int : String : Room + getNumber( ) + getName( ) + getRoom() + setName(aName : String) + setRoom(aRoom : Room) + toString( ) : int : String : Room : void : void : String Student(aName : String) : Student + isRenting() : Boolean tenant 0..1 rents 0..1 room - number - hall - tenant : int : String : Student + getNumber( ) + getHall( ) + setHall(aDescription : String) + toString( ) + isAvailable() + toString() : int : String : void : String : Boolean : String Room(aNumber : int, aHall : String): Room + rentTo(aTenant : Student) + isAvailable() /** Returns true if a student successfully rents a room … */ public Boolean rentTo(Student aTenant) { if ( this.isAvailable() ) { tenant = aTenant; aTenant.setRoom(this); return true; } else return false; } Now draw a sequence diagram to support this use case - are any new operations needed ? © De Montfort University Page 29 : Boolean : Boolean Object Technology Lecture 1 Notes Generalisation concepts and inheritance Learning Resources simple case study – “Student Accommodation” and UML class and object diagram examples. chalk / whiteboard Pens - for definitions, diagrams, string for connection and tracing etc. large paper class diagrams and or ‘hats’ (Room, Hall, Private) and large object diagrams (aRoom, aPrivateRoom, aHallRoom) to be held by some willing students who will simulate these classes and objects … Learning Outcomes Students should be able to: understand the UML notation for class inheritance understand OO concepts by 'acting out' using role play and or developing and drawing appropriate UML diagrams for simple specialisation / generalisation - based on modelling behaviour – not attributes (data), Discussion The concepts of generalisation, specialisation and inheritance will be discussed while investigating the development of the use case 'create a new tenancy agreement'. Understanding is often supported by developers active participation when they act out the role of objects by role playing different variants or scenarios of a use case. Initially this use case was developed above as a series of simple statements. A supporting object and class model was drawn along with examples of simple coded operations. A simplification of the 'rentTo' method of Room does not include the recording or checking of payment details. Initially emphasis should be placed on the examination of where the responsibility of 'renting' should be placed. During the development of the use cases to 'display a student's details' and to 'display the details of a room' it was found that both classes need to know about each other when participating in a renting association. It was therefore decided to implement a bi-directional association between Student and Room. It would now appear that since objects of both class can send messages to each other that either objects of the Student or Room class can be given the responsibility for 'renting' themselves to an object of the other class. Before a room can be rented two checks have to be made. That the room is available for renting and that the student is not currently renting a room. An operation 'isAvailable() : Boolean' has already been added to Room, a similar operation 'isRenting() : Boolean' will need to be added to Student. The rentTo method will have some responsibility for ensuring that these checks have been successful before being responsible for setting the bi-directional association. New attributes, operations and associations may be added to the model as the use case is developed. The diagrams below follow some of this development. use case 'create a new tenancy agreement' © De Montfort University Page 30 Object Technology Lecture 1 Notes Room - number - hall - rent - tenant Room - number - hall - rent - tenant : int : String : Money : Student + getNumber( ) + getHall( ) + getTenant() + setNumber(aNumber : int) + setHall(aHall : String) + isAvailable() + rentTo(aTenant : Student) + toString( ) Room(aNumber : int, aHall : String) : int : String : Student : void : void : Boolean : Boolean : String : Room : int : String : Money : Student + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean Where is the room ? How much is the rent ? number & hall rent : Money We need to modify the toString() operation to display rent. Often class diagrams are drawn with all get, set, display and constructor operations assumed …i.e. they are not shown - as above. © De Montfort University Page 31 Object Technology Lecture 1 Notes Room - number - hall - tenant - rent : int : String : Student : Money + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean Room - number : int - hall : String - tenant : Student - rent : Money - landlord : String - address : String - phoneNumber: String + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean When we examine the use case 'list details of private accommodation' we find that information is needed about the landlord's name and telephone contact number, address etc. These attributes will need to be added to Room and the toString method will need to be updated. © De Montfort University Page 32 Object Technology Lecture 1 Notes <<interface>> <<interface>> Student Room isRenting() : Boolean There are two pre-conditions that must be met before the rental of a room to a student is successful that the room is available for rent, it is not currently occupied that the student is not currently renting a room, the rentTo method in Room can be responsible for checking that the room is available either before the rentTo message is sent to a room a check can be made that the student is not already renting, or within the rentTo method a message could be sent to the student to check whether the student is currently renting etc. © De Montfort University Page 33 isAvailable() : Boolean rentTo(aTenant : Student) : Boolean /** Returns true if a student successfully rents a room. A pre-condition is that a student is not currently renting a room. */ public Boolean rentTo(Student aTenant) { if ( this.isAvailable() ) { tenant = aTenant; aTenant.setRoom(this); return true; } else return false; } Object Technology Lecture 1 Notes Development of the use case 'create a new tenancy agreement'. A problem exists - the university / the Student Accommodation System does not keep track of tenancy agreements between students and private landlords so the message 'aPrivateRoom.rentTo(aTenant)' must fail. 'aPrivateRoom' as far as the agency is concerned is never available for rent, or at least the agency has no knowledge of the rental agreement. We will need to decide how to ensure that a private room is never modelled as 'rented' in our system. Perhaps aPrivateRoom should always respond with 'false' when sent the message isAvailable, then the rentTo method would also return 'false'. For a private room we will need to alter isAvailable(). But how do we know if a room is a private room ? Within Room we could use an attribute as a ' flag'. ' privateRoom : Boolean ', or test if the attribute hall is equal to null. See below two different implementations of the method 'isAPrivateRoom'. For the use case 'is a room available for rent ?' a check is made to test whether the room is not a private room and does not currently have a tenant. If it is not a private room but a hall room and if it has no tenant then it is available for rent. public Boolean isAPrivateRoom() { return privateRoom ; } public Boolean isAPrivateRoom() { return hall == null ; } public Boolean isAvailable() { if ( !isAPrivateRoom() ) && ( tenant == null ) return true; else return false; } © De Montfort University Page 34 Room - number - hall - tenant - rent - landlord - address - phoneNumber - privateRoom : int : String : Student : Money : String : String : String : Boolean + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean Object Technology Lecture 1 Notes HallRoom - number - hall - tenant - rent - landlord - address - phoneNumber PrivateRoom : int : String : Student : Money : String : String : String + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean + toString() : String - number - hall - tenant - rent - landlord - address - phoneNumber : int : String : Student : Money : String : String : String + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean + toString() : String The object oriented approach differs from the above design that involves the testing and setting of attributes as flags. Instead two 'types' or class of room are modelled. Modelling of these rooms is based upon the different behaviour of aPrivateRoom and aHallRoom. The message rentTo(aStudent) can be sent to the receiver aHallRoom since it is part of the expected behaviour of aHallRoom to be rented. The expected result is either true or false. The message aPrivateRoom.rentTo(aStudent) must always result in false being returned. We can model two specialised types or class of room. The attribute 'privateRoom' is no longer needed, the implementation of the operation isAPrivateRoom will return true for PrivateRoom and false for HallRoom. © De Montfort University Page 35 Object Technology Lecture 1 Notes PrivateRoom HallRoom + isAvailable() + rentTo(aTenant : Student) + isAPrivateRoom() + toString() : Boolean : Boolean : Boolean : String aHallRoom : HallRoom privateRoom number hall tenant rent landlord address phoneNumber = = = = = = = = “false” 12 “New Lodge” null £45 null null null + isAvailable() + rentTo(aTenant : Student) + isAPrivateRoom() + toString() : Boolean : Boolean : Boolean : String aPrivateRoom : PrivateRoom privateRoom number hall tenant rent landlord address phoneNumber = = = = = = = = “true” null null null £35 Mrs Smith “2 High St” 555 6987 From the state of the above object diagrams we can see that the message aHallRoom.isAvailable() will return true. A hall room can be rented, the tenant attribute's state is null and so is available for rent. The message aPrivateRoom.isAvailable() must return false. Our system does not support / record private tenancy agreements. The tenant, hall and number attributes of a private room will always be set to null. The landlord, address and phone number of a hall room will always be set to null. We now find that we can delete these attributes, as indicated below. © De Montfort University Page 36 Object Technology Lecture 1 Notes HallRoom - rent - hall - number - tenant : Money : String : int : Student + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean + toString() : String <<HallRoom>> public Boolean isAPrivateRoom() { return false; } <<HallRoom>> public Boolean isAvailable() { if(tenant == null) return true; else return false; } © De Montfort University Page 37 PrivateRoom - rent - address - landlord - phoneNumber : Money : String : String : String + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean + toString() : String <<PrivateRoom>> public Boolean isAPrivateRoom() { return true; } <<PrivateRoom>> public Boolean isAvailable() { return false; } Object Technology Lecture 1 Notes Room - rent : Money + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + toString() : String HallRoom - rent - hall - number - tenant PrivateRoom : Money : String : int : Student - rent - address - landlord - phoneNumber + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean + toString() : String : Money : String : String : String + isAvailable() : Boolean + rentTo(aTenant : Student) : Boolean + isAPrivateRoom() : Boolean + toString() : String The Room class models general behaviour abstracted from the specialist types of hall and private room. Both subclasses have at least the attribute rent : Money in common. When implemented as a class inheritance hierarchy the Room super class is an integral part of both subclasses. © De Montfort University Page 38 Object Technology Lecture 1 Notes Room<<abstract>> # rent : Money # isAvailable() # rentTo(aTenant : Student) # isAHallRoom() # isAPrivateRoom() # toString() : Boolean : Boolean : Boolean : Boolean : String Hall - hall - number - tenant : String : int : Student + isAvailable() + rentTo(aTenant : Student) + isAHallRoom() + toString() © De Montfort University Private Page 39 - address - landlord - phoneNumber : Boolean : Boolean : Boolean : String : String : String : String + isAvailable() + isAPrivateRoom() + toString() : Boolean : Boolean : String Object Technology Lecture 1 Notes <<Room>> protected Boolean rentTo(aTenant :Student) { return false; } <<Room>> protected abstract Boolean isAvailable(); <<Hall>> public Boolean rentTo(Student aTenant) { if(this.isAvailable()) { tenant = aTenant; aTenant.setRoom(this); return true; } else return false; } <<Private>> private Boolean isAvailable() { return false ; } In a class hierarchy subclasses inherit the behaviour of their super class. A privateRoom is also a Room. A hallRoom is also a Room. Messages are always sent to the bottom of the hierarchy. The first method with the same operation signature as the message will be invoked. If an operation with the same signature is not found then the search continues up the hierarchy to the super class. A protected attribute or operation in a super class can be accessed by the subclass but is private to all classes outside the hierarchy. A private room cannot be rented. Any request to rent a private room must return false. The super class Room implements a protected operation rentTo(aTenant) that does no processing but simply returns false. The rentTo(aTenant) method is not implemented in the Private class and so any request to rent a private room is serviced by the method in Room that returns false. The rentTo(aTenant) operation in Hall has the same signature as the rentTo(aTenant) operation in Room, so any request to rent a hall room is serviced by the method in Hall. The method in Room is not invoked. The isAvailable operation in Room is abstract, it has no method body. An implementation of the method must be provided by all subclasses. Room provides some common behaviour for its subclasses. It is an abstract class. No objects of the class 'Room' can be instantiated since not enough functionality is provided. The operations isAHallRoom and isAPrivateRoom in Room always returns false. Why ? © De Montfort University Page 40 Object Technology Lecture 1 Notes rent available for rent aHallRoom.toString() rent contact aPrivateRoom.toString() £45 per week 56, College Av. phone £35 per week 16, Old Street Mrs Smith “2 High St” 555 6987 All classes are responsible for setting, getting and displaying their attributes. It is a convention that all Java classes provide a toString operation. The abstract class room is responsible for displaying the amount of rent charged for a room, so Room also provides a toString operation. The same toString message sent to either of the subclasses Private or Hall will result in the display of different types of information. Both sets of objects can respond polymorphically. The super class Room toString operation is not overridden but extended by the two subclasses. Within the toString methods of the subclasses a message is sent to the Room super class to display itself. © De Montfort University Page 41 Object Technology Lecture 1 Notes : Private :Room : Hall : Student :main toString() toString() the message to display a room and its details always goes first to the base class of the room hierarchy, a private room is responsible for displaying its own details, it then requests its super class to display itself the toString method is extended toString() toString() a hall room is responsible for displaying its own details, it then requests its super class to display itself the toString method is extended isAvailable() [isAvailable == "false"] toString() a hall may be rented, the hall requests the tenant to display itself toString() in Room is extended in Private & Hall The above sequence diagrams show the implementation of the message passing in the use case 'display a room and its details'. The diagram is an 'object sequence diagram', messages are passed to objects. A private room is an instance of both the Private and Room class, so we should not show Room as a separate entity - this is only added for the purpose of illustration. Both private and hall room objects of the Room class hierarchy can respond to the same toString message. These subclasses have a different implementation of the method - and so does the Student class, these are simple examples of polymorphism. © De Montfort University Page 42 Object Technology Lecture 1 Notes Preferred Drawing of Object Sequence Diagrams The diagrams below show the preferred way of drawing an 'object sequence diagram'. Messages are passed to objects. A private room is an instance of both the Private and Room class, so we do not show Room as a separate entity - this was only added for the purpose of illustration. : Private : Hall : Student :main a private room is responsible for displaying its own details, it then requests its super class to display itself the toString method is extended toString() toString() a hall room is responsible for displaying its own details, it then requests its super class to display itself the toString method is extended isAvailable() [isAvailable == "false"] toString() a hall may be rented, the hall requests the tenant to display itself toString() in Room is extended in Private & Hall Both private and hall room objects of the Room class hierarchy can respond to the same toString message. These subclasses have a different implementation of the method - and so does the Student class, these are simple examples of polymorphism. © De Montfort University Page 43 Object Technology Lecture 1 Notes Use case 'create a new tenancy' aStudent : Student aRoom: Hall :main Room isRenting() a student knows if it is currently renting a room if not renting the student requests the room to rent itself [ isRenting == "false"] setRoom(self) a room can ask itself if it is available if available a room can set its tenant attribute to 'aStudent' and ask the student to set the room (self) to its room attribute © De Montfort University rentTo(aStudent) Page 44 isAvailable() [ isAvailable == "true"] { tenant := aStudent } Object Technology Lecture 1 Notes Use case 'create a new tenancy' aStudent : Student aRoom: Private :main Room a student knows if it is currently renting a room if not renting the student requests the room to rent itself isRenting() [ isRenting == "false"] [rentTo == "false"] a private room cannot rent itself to a student - it returns false © De Montfort University rentTo(aStudent) Page 45 Object Technology Lecture 1 Notes Use case 'create a new tenancy' aStudent : Student aRoom: Private aRoom: Room :main Room a student knows if it is currently renting a room if not renting the student requests the room to rent itself isRenting() [ isRenting == "false"] rentTo(aStudent) rentTo(aStudent) a private room cannot rent itself to a student - it returns false [rentTo == "false"] aPrivateRoom object is both an instance of the Private and Room class this diagram shows the implementation of message passing, but as an 'object sequence diagram' the class Room should not be shown © De Montfort University Page 46 Object Technology Lecture 1 Notes Aggregation and Composition Learning Resources UML use cases statements, object and class diagram examples, sequence diagrams, notes on aggregation chalk / whiteboard Pens - for definitions, diagrams etc. Learning Outcomes Students should be able to: understanding associations, aggregation as a whole - part association and composition as a relationship when the whole and parts existence is inter-dependant for a simple use case statement to display objects' details and their parts involving delegation, develop and draw appropriate class, object and sequence diagrams Lecturer " a lecturer mentors zero , one or many students a student is mentored by zero or one lecturer " Student mentor A simple zero or one to many association, the arrow indicates navigation, we can send a message from a lecturer to any or all students … this implies that there must be a collection of students as an attribute in Lecturer. name e-mail students : String : String : Collection 0..1 mentors * : int : String as an extension to the case study ' A University Student Accommodation Agency' Discussion A collection acts as a container for example Array[ 9 ] holds 10 elements, typically positions 0-9 Vector holds any number of elements - dynamic Collections typically have common behaviour , they can respond to messages such as add(anObject) modify(anObject) remove(anObject) get() a lecturer is appointed to act in the 'role' of a mentor to a group of students if the agency needs to contact the student e.g. in an emergency then we need to keep track of the association between a lecturer and the students he or she is responsible for Sometimes aCollection will be responsible for remembering where each element is with such operations as getFirstElement(), getLastElement() We will know how many elements are in the collection by using operations such as - isEmpty():Boolean, isFull():Boolean, size():int © De Montfort University number name Page 47 Object Technology Lecture 1 Notes 'students' is a collection of Student objects, students:Collection We can use the behaviour of the collection to implement some use cases … "display all the details of students a lecturer mentors" "a lecturer mentors another student" "check if a student is mentored by a lecturer" "how many students does a lecturer mentor ? " - aLecturer.displayAllStudents(); aLecturer.add(aStudent); aLecturer.isMentoring(aStudent); aLecturer.numberIsMentoring(); When developing the use case "display all the details of all students a lecturer mentors" the use case is described as a set of sequences of actions, including variants. From this set of statements we can identify the lecturer student association and the need for a collection object. 1. aLecturer object is responsible for knowing its name, e-mail etc. aLecturer can display its name … 2. aLecturer is responsible for knowing the number of students it is mentoring, aLecturer is not responsible for knowing the details of its students, aLecturer delegates the display of student details to each student 3. if aLecturer is not mentoring any students the message "is not mentoring any students" is displayed else the message "is mentoring a number of students" is displayed 4. aStudent is responsible for knowing its number and name aStudent can display its number and name each student displays its own details … © De Montfort University Page 48 Object Technology Lecture 1 Notes aLecturer : Lecturer aStudent : Student :main if aLecturer is mentoring some students, the lecturer sends a message to each student to display itself - displayAllStudents() Room size( ) [ students.size != 0 ] 'students' as a collection will be responsible for knowing how many objects / students it contains - * { While anIterator.hasNext() } toString( ) all student objects display themselves, they are sent a toString message Lecturer - name - e-mail - students : String : String : Collection + displayAllStudents() + toString() : String : String Collection << uses >> + isEmpty() + size() + isFull() + add(anObject) + remove(anObject) + hasNext() : Boolean : int : Boolean : void : void : Boolean A collection 'uses' or is implemented by a collection class. Typically collection classes are provided as part of an object oriented language such as Smalltalk, Java or C++. © De Montfort University Page 49 Object Technology Lecture 1 Notes <<Lecturer>> public String displayAllStudents() { String lecturerDetails = name + "\n" + "e-mail" + e-mail + "\n"; if(students.isEmpty()) return lecturerDetails += " is not mentoring any students. \n"; else if (students.size() == 1) lecturerDetails += " is mentoring one student :- \n"; else lecturerDetails += " is mentoring " + students.size() + " students :- \n"; Student aStudent; ListIterator anIterator = students.listIterator(); While( anIterator.hasNext() ) { aStudent = ( (Student) anIterator.next() ); lecturerDetails += aStudent.toString() + "\n"; } return lecturerDetails; } An implementation of the displayAllStudents() method of Lecturer. Messages such as isEmpty and size are sent to 'students' - an instance of a collection class. The collection class implements a list of objects, anIterator refers to the next object in this list. A student is an object sent a toString message. © De Montfort University Page 50 Object Technology Lecture 1 Notes aLecturer1 : Lecturer aStudent1 : Student name e-mail students = "Smith" = "smith@dmu.ac.uk" = [ aStudent1, aStudent2 ] number name room = 1235 = "Kate" = aRoom aStudent2 : Student number name room = 6789 = "Bill" = null Lecturers are responsible for displaying their names, email accounts and the number of students they are mentors for, aLecturer1 is associated with two students. It is the student objects that know and are responsible for displaying the state of their attributes. © De Montfort University Page 51 Object Technology Lecture 1 Notes Lecturer - name - e-mail - students Student : String : String : Collection 0..1 + displayAllStudents() : String + toString( ) : String + addStudent(aStudent : Student) : void Dr Smith e-mail smith@dmu.ac.uk is mentoring two students :Student # 1235 Kate is renting a hall room at 12 New Lodge Student # 6789 Bill is not renting a hall room © De Montfort University Page 52 mentors * - number nextNumber - name - room : int : int : String : Room + getNumber( ) : int + getName( ) : String + setName(aName : String) : void + toString( ) : String Student(aName : String) : Student Object Technology Lecture 1 Notes LecturerBase - lecturers : Collection + displayAllLecturers() + addNewLecturer(aName: String, e-mail : String) + addStudent(aLecturerName : String, aStudent : Student) : String : String : String 1 contains 0 .. * Lecturer Student - name - e-mail - students : String : String : Collection + getName() + getE-mail() + displayAllStudents() + addStudent(aStudent : Student) + toString() + Lecturer(aName : String, e-mail : String) : String : int : String : String : String : Hall 0..1 mentors * - number nextNumber - name - room : int : int : String : Room + getNumber( ) + getName( ) + setName(aName : String) + toString( ) Student(aName : String) : int : String : void : String : Student Aggregation - (contains) use case "display a list of all lecturers and their students" LecturerBase acts as a wrapper, wrapping a collection attribute 'lecturers' that can contain a number of lecturer objects. 'aLecturerBase' is responsible for all lecturers, it is an aggregation of lecturers. The message displayAllLecturers is sent to the lecturerBase, each lecturer in the base in turn is sent the message displayAllStudents, in turn again every lecturer requests their students to display themselves using the toString message. © De Montfort University Page 53 Object Technology Lecture 1 Notes lecturers lecturers : LecturerBase [ aLecturer1, aLecturer2 , aLecturer3 ] = aLecturer3: Lecturer name = "White" e-mail = "white@dmu.ac.uk" students = [ aStudent4, aStudent6 ] aLecturer1 : Lecturer name = "Smith" e-mail = "smith@dmu.ac.uk" students = [ aStudent1, aStudent2 ] aLecturer2 : Lecturer name = "Brown" e-mail = "brown@dmu.ac.uk" students = [ ] aStudent2 : Student number = 6789 name = "Bill" room = null aStudent1 : Student number = 1235 name = "Kate" room = aRoom The object diagram above shows a lecturerBase with one attribute 'lecturers', a collection containing three lecturer objects. A lecturerBase is responsible for displaying the number of lecturer objects in its collection. Lecturers are responsible for displaying their names, email accounts and the number of students they are mentors for, aLecturer1 is associated with two students, aLecturer2 object is associated with no students, aLecturer3 object is associated with two students - not shown on the diagram. It is the student objects that know and are responsible for displaying the state of their attributes. © De Montfort University Page 54 Object Technology Lecture 1 Notes lecturers: LecturerBase : Lecturer Room Room : Student :main displayAllLecturers() use case size() " display details of all lecturers and the students they are mentors for " [ lecturers.size ! = 0 ] aLectureBaser is an aggregation of lecturers, 'lecturers' as a collection is responsible for knowing how many objects / lecturers it contains - all lecturer objects can display themselves, each object is sent a message to display itself, * { While anIterator.hasNext() } displayAllStudents() size() [ students.size ! = 0 ] each lecturer displays its own details, then if aLecturer is mentoring some students, the lecturer sends a message to each student to display itself - * { While anIterator.hasNext() } toString( ) 'students' as a collection will be responsible for knowing how many objects / students it contains - all student objects display themselves, they are sent a toString message © De Montfort University Page 55 Object Technology Lecture 1 Notes AccommodationAgency - aLecturerBase - aStudentBase : LecturerBase : StudentBase + displayAllLecturers() + displayAllStudents() : String : String 1 is composed of 1 1 LecturerBase StudentBase - lecturers : Collection - students : Collection + displayAllLecturers() : String + displayAllStudents() : String 1 contains 0 .. * 1 contains 0 .. * Lecturer - name - e-mail - students : String : String : Collection Student mentor 0..1 mentors * + displayAllStudents() + toString() : String : String - number nextNumber - name - room : int : int : String : Room + toString( ) : String Composition a special form of aggregation An accommodation agency is a special form of aggregation, it is 'composed' of two lists or bases; aLectureBase and aStudentBase. Each base is an aggregation of objects that 'contain' either lecturers or students. A lecturer is a mentor for zero, one or many students. The lecturer - student association is not a whole-part association. Aggregation refers to a whole-part association whereby the aggregation as a whole contains a number of parts. Each part exists independently of the whole. The whole aggregate may at sometime contain no participating part objects aLecturerBase is empty. Composition refers to a whole-part association whereby the composition as a whole is composed of a number of parts. The whole and each part do not exist independently of each other. The whole must have parts to exist - part objects participate in only one whole association. If either the whole or part objects are destroyed, then the other whole or part objects are destroyed. © De Montfort University Page 56 Object Technology Lecture 1 Notes Class Responsibility and Collaboration (CRC cards) Learning Resources a problem statement or case study (Bank), CRC cards, object, class and sequence diagrams Learning Outcomes Students should be able to: understand how to role play 'objects' that respond to message passing when using CRC cards appreciate through the role play of use case(s) how responsibilities are allocated to classes and recorded on CRC cards Discussion While developing use cases as a sequence of statements decisions have to be made to allocate these statements as responsibilities (behaviours and attributes) to classes. For a bank case study a first draft object and class diagram is given below. An investigation into how use cases are implemented can be achieved by designers playing the role of 'objects' in response to message passing. As understanding is gained through role play, responsibilities and collaborators are identified and recorded on CRC cards (Class, Responsibility, Collaborators). Class models and sequence diagrams can then be updated to show the static and dynamic nature of the realisation / implementation of these uses cases. Class : Responsibilities use cases - Collaborators "add a new customer to the bank" "check if an account with a given number exists" "list all the accounts of a customer" "debit an account" The first use case is developed below. © De Montfort University Page 57 Object Technology Lecture 1 Notes aBank : Bank aCustomerBase anAccountBase = BankCustomerBase = AccountsBase aCustomerBase : BankCustomerBase anAccountBase : AccountBase [ customer1, customer2, customer3, …] [ savings1, current1, savings2, current2, savings3] customer1 : BankAccountCustomer name = "Trevor" age = 23 gender = 'M' accounts = [savings1, current1] current1 : Current number = 1002 balance = 10 overdraft = 500 owner = customer1 customer3 : BankAccountCustomer name = "Stuart" age = 33 gender = 'M' accounts = [savings3] savings3 : Savings number = 1004 balance = 1000 interestRate = 5 owner = customer3 customer2 : BankAccountCustomer name = "Eva" age = 21 gender = 'F' accounts = [savings2, current2] savings2 : Savings number = 1003 balance = 780 interestRate = 10 owner = customer2 © De Montfort University savings1 : Savings number = 1001 balance = 200 interestRate = 5 owner = customer1 Page 58 current2 : Current number = 1004 balance = -100 overdraft = 100 owner = customer2 Object Technology Lecture 1 Notes Bank BankCustomerBase AccountBase Person BankAccount BankAccountCustomer Current © De Montfort University Page 59 Savings Object Technology Lecture 1 Notes use case 'add a new customer to the bank' Develop as a narrative the use case 'add a new customer to the bank'. "Anita goes to a bank and enquires at the cashier's desk if she can open a savings account. She is asked if she already has an account. Anita replies that she does not have an account. She is told that the bank will need to take some details before she can open the new account." A narrative or 'essential' use case is simply part of a story. We talk about real instances, 'objects' in the world. This is an instance of one variant or scenario of the use case to add a new customer to the bank. In this simple case study no two customers with the same name can exist, customers are uniquely identified by name. We have assumed that only details about a customer's name are recorded. Later discussions would include gathering further customer details. A check that an object representing the customer did not already exist would be made before all the details were entered. Development of the narrative use case as a sequence of statements 1. enter the name of the 'potentially' new bank customer, 2. the bank checks if it already includes a customer with this name, if after searching through all the customers no customer exists with this name then a new customer object to represent the customer can be created, 3. create a new customer object with the given name to represent a new bank customer, 4. add this new customer object to the bank, 5. return a message from the bank confirming the addition of the new customer, Objects (12) players Play the role of objects, each player has a CRC card theBank aCustomerBase anAccountBase customer1 customer2 customer3 savings1 savings2 savings3 current1 current2 current3 : Bank : BankCustomerBase : AccountBase : BankAccountCustomer : BankAccountCustomer : BankAccountCustomer : Savings : Savings : Savings : Current : Current : Current a thirteenth player is needed to act the role of the new customer object © De Montfort University Page 60 Object Technology Lecture 1 Notes 1. it is the responsibility of the bank application to deal with data input and output enter the name of the 'potentially' new bank customer, the bank delegates the responsibility of adding a new customer to the bank, to its collection of customers, a aCustomerBase, the bank sends a message to aCustomerBase to add a new customer with this name 2. aCustomerBase, as an instance of BankCustomerBase has a collection of customer objects, it is responsible for knowing if it has any objects in its collection, but it is not responsible for knowing about the details; state or behaviour of these objects, a collection can self delegate messages to itself such as size() isEmpty() the bank checks if it already includes a customer with this name aCustomerBase collaborates with each customer object to check if it already includes a customer with this name, aCustomerBase repeatedly sends a message to each object in its collection, each customer object is asked for its name, all customer objects are responsible for knowing their names, aCustomerBase is responsible for checking whether the name of a customer (s) is the same as the name of the new potential customer if after searching through all the customers no customer exists with this name then a new customer object to represent the customer can be created, 3. aCustomerBase delegates this responsibility by collaborating with the Customer class by requesting the Customer class to construct a new customer with a given name, (a class is responsible for constructing instances of itself), create a new customer object with the given name to represent a new bank customer the Customer class returns a new customer object with a name, 4. aCustomerBase is responsible for adding this new customer object to its collection of customers, add this new customer object to the bank, 5. aCustomerBase delegates the responsibility of displaying a message to the user of the system to the banking application by returning a message to the bank confirming the addition of the new customer object, return a message from the bank confirming the addition of the new customer, the bank is responsible for displaying a message to confirm of the addition of a new customer to the bank © De Montfort University Page 61 Object Technology Lecture 1 Notes Class : BankCustomerBase Responsibilities Collaborators knows how many objects are in the collection check if it includes an object BankAccountCustomer add new objects to itself confirm addition to the collection Bank … Class : Customer Responsibilities Collaborators can display itself and ask each of its accounts to display themselves BankAccount and subclasses knows how many accounts it has can create instances of itself … If other use cases are played e.g. transfer - then the state of the object players' diagrams can be updated For the use case "add a new customer" note how it is the class Customer that is responsible for constructor the new customer object - customer4 is returned (another player is needed to act this role). It is the responsibility of the aggregation class aCustomerBase to add this new object to its collection of customers. © De Montfort University Page 62 Object Technology Lecture 1 Notes Development of a conceptual model Learning Resources a problem statement or case study (university accommodation agency), use cases, object and class diagrams Learning Outcomes Students should be able to: understand how to distinguish conceptual analysis models from design class models appreciate when attempting to realise use cases that a variety of competing modelling decisions can be made Discussion use case 'create a new tenancy agreement' rent a room to a student - (assume a student is already on the system) Actor (agency officer) Action System Response 1 - type in a password 3 - select create new tenancy 5 - enter student number / name 2 - present menu / windows 4 - prompt for student number / name 6 – check / find if student is on the system 7 - check is eligible to rent (not renting, no rent arrears) 9 - check room is available to rent (not currently rented) 10 - add payment details 11 - rent room to student 12 - display confirmation - tenancy created 8 - enter room unique identifier Object modelling aStudent : Student number name aRoom : Hall = 6789 = "Bill" number address = 56 = "College Av." aTenancy : Tenancy startDate endDate payments = 23.9.99 = =… We need to capture date and payment details about a tenancy agreement. These details are not logically the responsibility of either the Student or Room classes. © De Montfort University Page 63 Object Technology Lecture 1 Notes Conceptual model These details refer to a new link association, created when the tenancy / room is rented. We can initially model this association as a new link class. Room Student - name 0 .. 1 can rent 0 .. 1 : String + isRenting( ) : Boolean # rent : Money # isAvailable() # rentTo(aTenant : Student) # isAHallRoom() # isAPrivateRoom() : Boolean : Boolean : Boolean : Boolean Tenancy - startDate - endDate - payments : Date : Date : Money Hall Private - hall - number : String : int - address - landlord - phoneNumber : String : String : String + isAvailable() + rentTo(aTenant : Student) + isAHallRoom() : Boolean : Boolean : Boolean + isAvailable() + isAPrivateRoom() : Boolean : Boolean + isOverdue() : Boolean We need to examine a series of use cases to see if they are supported by this model. As use cases are developed as a series of statements we move from an initial conceptual model referring to our analysis of what the model must support to a design model. We will include decisions about navigation from one class of objects to another. The above analysis diagram does not include attributes to implement associations. Frequently class diagrams omit many operation signatures such as get, set and constructors, for the above Student class the operations getName( ) : String setName(aName : String) : void Student(aName : String) : Student are assumed and are not drawn. All java implementations also include a toString( ) : String operation for all classes. © De Montfort University Page 64 Object Technology Lecture 1 Notes Room Student - name - tenancy : String : Tenancy + isRenting( ) + toString( ) : Boolean : String 0 .. 1 can rent 0 .. 1 # rent : Money # isAvailable() # rentTo(aTenant : Student) # isAHallRoom() # isAPrivateRoom() # toString() : Boolean : Boolean : Boolean : Boolean : String Tenancy - startDate - endDate - payments : Date : Date : Money - room : Room toString() : String Hall Private - hall - number : String : int - address - landlord - phoneNumber : String : String : String + isAvailable() + rentTo(aTenant : Student) + isAHallRoom() + toString() + isOverdue() : Boolean : Boolean : Boolean : String : Boolean + isAvailable() + isAPrivateRoom() + toString() : Boolean : Boolean : String From the use case 'is a student renting a room' we find that Student will need an attribute 'tenancy' to indicate whether the student is renting. This tenancy attribute is not a simply a piece of data like a character or an 'int' but is an object of the class Tenancy, drawn as tenancy : Tenancy. The isRenting method will test if this tenancy attribute is null. If not null then the student is renting a room. From the use case 'display a student and their details' we find that to display the details of a student the toString method in Student should delegate displaying tenancy details to the tenancy object. Tenancy should further delegate responsibility of displaying the details of the room to a room : Room attribute in tenancy. © De Montfort University Page 65 Object Technology Lecture 1 Notes Room Student 0 .. 1 can rent 0 .. 1 - name : String + isRenting( ) : Boolean # rent : Money # isAvailable() # rentTo(aTenant : Student) # isAHallRoom() # isAPrivateRoom() : Boolean : Boolean : Boolean : Boolean Tenancy - startDate - endDate - payments - tenant : Date : Date : Money : Student + toString : String Hall Private - hall - number - tenancy : String : int : Tenancy - address - landlord - phoneNumber : String : String : String + isAvailable() + rentTo(aTenant : Student) + isAHallRoom() + toString( ) + isOverdue() : Boolean : Boolean : Boolean : String : Boolean + isAvailable() + isAPrivateRoom() : Boolean : Boolean From the use case 'is a room available to rent' we find that Hall will need an attribute 'tenancy' to indicate whether the room is currently being rented. This tenancy attribute again is not a simply a piece of data like a character or an 'int' but is an object of the class Tenancy, drawn as tenancy : Tenancy. The isAvailable method will test if this tenancy attribute is null. If not null then the room is rented. From the use case 'display a room and its details' we find that to display the details of a hall room the toString method in Hall will delegate displaying tenancy details to the tenancy object. Tenancy will further need to delegate responsibility of displaying the details of the student who is renting the room to an attribute tenant : Student attribute in tenancy. The above association between student and room could now be redrawn with an arrow at both ends to indicate twoway navigation between these classes. The approach taken in the UML with a design model is to omit the attributes needed to implement an association but to include the double headed arrow. We will include both annotations to our diagrams. Annotate the above diagram. © De Montfort University Page 66 Object Technology Lecture 1 Notes Room Student - name - tenancy : String : Tenancy + isRenting( ) + toString : Boolean : String 0 .. 1 can rent 0 .. 1 # rent : Money # isAvailable() # rentTo(aTenant : Student) # isAHallRoom() # isAPrivateRoom() # toString : Boolean : Boolean : Boolean : Boolean : String Tenancy - startDate - endDate - payments - tenant - room : Date : Date : Money : Student : Room + toString : String Hall Private - hall - number - tenancy : String : int : Tenancy - address - landlord - phoneNumber : String : String : String + isAvailable() + rentTo(aTenant : Student) + isAHallRoom() + toString( ) + isOverdue() : Boolean : Boolean : Boolean : String : Boolean + isAvailable() + isAPrivateRoom() : Boolean : Boolean For the use case 'display all tenancy agreements where rent is overdue' we will need to iterate through all tenancy agreements. Either we will implement an aggregation of tenancy agreements such as 'tenancies : TenancyBase' or we will access each agreement via hall rooms or student object links to tenancy objects. The isOverdue method in Room is accessed via the 'room' attribute in Tenancy. The isOverdue method needs to use the rent : Money attribute in Room and the date and payments attributes in Tenancy. Perhaps we should move this isOverdue operation from Hall to Tenancy, it is the payment of the tenancy that can be overdue not the hall room. This gives rise to a need to find out whether a history of tenancy agreements should be stored. A student may owe rent for a room rented in a previous year, while the room is currently rented out to another student - not in rent arrears. The isOverdue method should return false for the current tenancy and true for the previous tenancy. Should we now amend the multiplicity between Student and Room ? For the use case 'rent a room to a student / create a new tenancy agreement' the Tenancy constructor signature will be tenancy = new Tenancy(startDate, endDate, payments, tenant, room); A tenancy agreement includes details of not only dates and payments but also the tenant and room. © De Montfort University Page 67 Object Technology Lecture 1 Notes A link class is one possible solution. Let us ignore the possibility of storing a history of tenancy agreements. The multiplicity between the Student and Room classes will remain the same. We can now redesign the model and omit the Tenancy link class. We no longer need a Tenancy attribute in Student or Room. Possibly a tenancy attribute is placed in Student and Room, this will depend upon a re-investigation of the previous use cases. Room Student - name - tenancy : String : Hall + isRenting( ) + toString : Boolean : String 0 .. 1 can rent 0 .. 1 # rent : Money # isAvailable() # rentTo(aTenant : Student) # isAHallRoom() # isAPrivateRoom() # toString : Boolean : Boolean : Boolean : Boolean : String Hall © De Montfort University Private - hall - number - tenant - startDate - endDate - payments : String : int : Student : Date : Date : Money + isAvailable() + rentTo(aTenant : Student) + isAHallRoom() + toString( ) + isOverdue() : Boolean : Boolean : Boolean : String : Boolean Page 68 - address - landlord - phoneNumber : String : String : String + isAvailable() + isAPrivateRoom() : Boolean : Boolean Object Technology Lecture 1 Notes Use case driven design Learning Resources UML use case statements, object and class diagram examples, sequence diagrams Learning Outcomes Students should be able to: understand delegation and responsibility understand the need for decisions in design Discussion "a university student in an academic year registers to study four different modules per semester. There is initially no limit to the number of students who can be taught on a module." UniversityApplication 1 is composed of 1 1 ModuleBase StudentBase 1 contains 0 .. * 1 contains 0 .. * Module 0..1 studied by 0 ..* Student use case 'register a student for a module' There are many ways to realise this use case. As a sequence of statements i ii iii iv v vi get the object representing the student check the student is registered for less than four modules check the student is not already registered for this module get the object representing the module check the module has less than the maximum number of students registered to study it register the student on this module Which class is responsible for getting the objects ? Which classes have the responsibility for undertaking the checking - do they delegate ? Which class is responsible for registering a student on a module ? We know these activities need to occur but we can achieve the same result in many ways. These are design decisions. Allocating responsibilities Below are four different ways of allocating responsibilities throughout the system - © De Montfort University Page 69 Object Technology Lecture 1 Notes 1. The UniversityApplication is made responsible for the use case to register a student for a module. Here the University Application is active while Student and Module objects are passive holders of data with little responsibility. use case 'register a student for a module' the universityApplication gets the student and module objects, the universityApplication checks the student and module, then the universityApplication registers the student and module Each of these statements can be further developed as a series of use cases and statements, for example use case 'get the student' enter a unique identifier (#number, name) check if the collection of students includes a student with this number, return this student object responsibility - UniversityApplication responsibility - StudentBase collection responsibility - Student use case 'check the student is registered for less than four modules' the UniversityApplication sends a message to the student to enquire about how many modules the student is currently registered for responsibility - UniversityApplication responsibility - Student aStudent.numberOfModulesRegisteredFor() use case 'check the student is not already registered for this module' the UniversityApplication sends a message to the student to enquire if the student is currently registered for the module responsibility - UniversityApplication responsibility - Student aStudent.isRegisteredFor(aModule) use case 'get the module' enter a unique identifier (#number) check if the collection of modules includes a module with this number, return this module object responsibility - UniversityApplication responsibility - ModuleBase collection responsibility - Module use case 'check the module has less than the maximum number of students registered to study it' the UniversityApplication can send messages to the module to enquire if the module is full responsibility - UniversityApplication responsibility - Module aModule.maximumRegistration() aModule.numberRegistered() use case 'register a student on a module' the UniversityApplication has successfully checked that a student module registration will be successful, so the registration can be completed aStudent.register(aModule) aModule.register(aStudent) © De Montfort University Page 70 responsibility - UniversityApplication Object Technology Lecture 1 Notes 2. The UniversityApplication is made responsible for the use case to register a student for a module. Here the University Application is less active, the Module object is still a passive holder of data with little responsibility while the student actively checks and registers itself. use case 'register a student for a module' the universityApplication gets the module object, the universityApplication checks the module, then the universityApplication requests the module to register itself with the student (the student checks itself) Each of these statements can be further developed as a series of use cases and statements, for example use case 'get the module' enter a unique identifier (#number) check if the collection of modules includes a module with this number, return this module object responsibility - UniversityApplication responsibility - ModuleBase collection responsibility - Module use case 'check the module has less than the maximum number of students registered to study it' the UniversityApplication can send messages to the module to enquire if the module is full responsibility - UniversityApplication responsibility - Module aModule.maximumRegistration() aModule.numberRegistered() use case 'register a student on a module' the UniversityApplication has successfully checked that a module can register a student, the UniversityApplication delegates the responsibility of getting the student object to the studentBase, the studentBase is sent the module object with a request to register the student to itself, the student is responsible for checking itself that it is registered for less than four modules and is not already registered for this module, if successful then the student and module can register themselves aStudentBase.register(aModule,"Bill"); aStudent.canRegisterFor(aModule); aStudent.register(aModule) or aModule.register(aStudent) © De Montfort University Page 71 responsibility - UniversityApplication responsibility - StudentBase collection responsibility - Student responsibility - Student and Module Object Technology Lecture 1 Notes 3. The UniversityApplication is made responsible for the use case to register a student for a module. Here the University Application is less active, the Student object is still a passive holder of data with little responsibility while the module actively checks and registers itself. use case 'register a student for a module' the universityApplication gets the student object, the universityApplication checks the student, then the universityApplication requests the student to register itself with the module (the module checks itself) Each of these statements can be further developed as a series of use cases and statements, for example use case 'get the student enter a unique identifier (#number, name) check if the collection of students includes a student with this name, return this student object responsibility - UniversityApplication responsibility - StudentBase collection responsibility - Student use case 'check the student is registered for less than four modules' the UniversityApplication sends a message to the student to enquire about how many modules the student is currently registered for responsibility - UniversityApplication responsibility - Student aStudent.numberOfModulesRegisteredFor() use case 'check the student is not already registered for this module' the UniversityApplication sends a message to the student to enquire if the student is currently registered for the module responsibility - UniversityApplication responsibility - Student aStudent.isRegisteredFor(aModule) use case 'register a student on a module' the UniversityApplication has successfully checked that a student can be registered on the module, the UniversityApplication delegates the responsibility of getting the module object to the moduleBase, the moduleBase is sent the student object with a request to register the student to itself, the module is responsible for checking itself it knows the maximum number of students that can register for the module and the number of students that have registered for the module, so it can be responsible for knowing if the module is full, if successful then the student and module can register themselves aModuleBase.register(aStudent,129; aModule.canRegisterAnotherStudent(); aStudent.register(aModule) or aModule.register(aStudent) © De Montfort University Page 72 responsibility - UniversityApplication responsibility - ModuleBase collection responsibility - Module responsibility - Student and Module Object Technology Lecture 1 Notes 4. The UniversityApplication delegates the responsiblity for the use case to register a student for a module. Here the University Application is not active, the Student and Module objects are holders of data and also have the responsibility to actively check and register themselves to each other. use case 'register a student for a module' the universityApplication gets the student or the module object, the universityApplication sends the student to the moduleBase or sends the module to the studentBase, the student attempts to register itself with the module or vice-versa (the module and student check themselves) Each of these statements can be further developed as a series of use cases and statements, for example use case 'get the student' enter a unique identifier (#number, name) check if the collection of students includes a student with this name, return this student object responsibility - UniversityApplication responsibility - StudentBase collection responsibility - Student use case 'register a student on a module' the UniversityApplication delegates the responsibility of registering the student for a module to the moduleBase, the moduleBase is sent the student object with a request to register the student to itself, the module is responsible for checking itself it knows the maximum number of students that can register for the module and the number of students that have registered for the module, so it can be responsible for knowing if the module is full, the student is responsible for checking itself that it is registered for less than four modules and is not already registered for this module, if successful then the student and module can register themselves responsibility - ModuleBase collection responsibility - Module responsibility - Student responsibility - Student and Module aModuleBase.register(aStudent,129; aStudent.register(aModule) or aModule.register(aStudent) This fourth way of allocating responsibilities is preferred, there are no passive objects, behaviour and data are closely tied together. The UniversityApplication is responsible for processing requests and data entered by users of the system and for displaying returned messages to these users. The StudentBase and ModuleBase encapsulate collections of objects. These two classes are responsible for general collection tasks such as retrieving and adding objects from and to these collections. The Student and Module classes are responsible for the checking and actual registration. The data needed to process these use cases is encapsulated in these classes, so the responsibility to process these uses cases can be allocated to these classes. Any change to the rules governing registration will result in little change to the overall system. For example if the number of modules a student can study is increased then a change will only be made to the Student class. The UniversityApplication and StudentBase have no responsibility or knowledge of the number of modules a student can study and so this change does not alter these classes. © De Montfort University Page 73 Object Technology Lecture 1 Notes 'register a student for a module' modules: ModuleBase :University Application main register(aStudent,129)Room * getModule(129) : Module : Student Room this diagram assumes that a universityApplication has already retrieved a student object from the studentBase, [ getNumber( ) == 129 ] the universityApplication having retrieved a student object then delegates responsibility for registration to the moduleBase, registerFor(aModule) the moduleBase is sent the student object and the unique identifier of the module, the moduleBase attempts to get the module, canRegisterForAnotherModule() isRegisteredFor(aModule) register(aStudent) the student is requested to register for the module, the student is responsible for knowing if it can register for another module and if it is already registered for this module, canRegisterAnotherStudent() add(aStudent) the module is requested to register the student, it is responsible for knowing whether it can register another student, add(aModule) the module adds the student to its collection of students, the student adds the module to its collection of modules © De Montfort University Page 74 Object Technology Lecture 1 Notes " a university student in an academic year registers to study four different modules per semester. There are a initially no limits to the number of students who can be taught on a module." use case 'register a student for a module' Module Student MAXMODULES - number - name - modules : int : int : String : Collection + registerFor(aModule) : void + canRegisterForAnotherModule( ) : Boolean + isRegisteredFor(aModule) : Boolean - add(aModule) : void 0..* register for 0..4 MAXREGISTRATION - code - title - students : int : String : String : Collection + register(aStudent) + canRegisterAnotherStudent( ) - add(aStudent) : void : Boolean : void A student knows the maximum number of modules it can register for, it has a collection of modules and so knows how many modules it is registered for and can find out what they are. A module knows the maximum number of students that can be registered for a module, it has a collection of students and so knows how many students are registered for a module. A student is responsible for registering for a module. The student has two operations used to check whether it can register for the given object, if these operations return true then the given module can be requested to register the student. A module is responsible for knowing if it can register more students. Both student and module have two private add operations, used to link each other together - the registration. Only once the above pre-conditions or checks are fulfilled can the registration be completed. " at the start of an academic year a limit is set to the number of students who can be taught on a module. This limit depends upon the availability of staff, rooms and computing resources. Students who registered late will need to re-register for another module." use case 're-register a student for a module' How do we know which students registered first for a module ? We could add a date of registration attribute. Where do we place this attribute ? We could add a new link class between both student and module. Alternatively if the attribute 'students : Collection' was implemented as an ordered collection , then those students in the front of the collection can be identified as the students who were first to register for the module. If the MAXREGISTRATION was 70, those after 70 in the collection would need to be re-registered. This design decision means that no link class is now needed. © De Montfort University Page 75 Object Technology Lecture 1 Notes " the university wants to record students' module grades. A student may retake a module many times, all grades are to be recorded along with the semester and academic session they were achieved. " use case 'record a grade for a student' Student Module MAXMODULES - number - name - assessment : int : int : String : Collection + registerFor(aModule, aSemester, aSession) + canRegisteredForAnotherModule( ) + isRegisteredFor(aModule, aSemester, aSession) - add(aModule, aSemester, aSession) + add(aGrade, aModule, aSemester, aSession) : void : Boolean : Boolean : void : void 0..* register for 0..* MAXREGISTRATION - code - title - assessment : int : String : String : Collection + register(aStudent, aSemester, aSession) + canRegisterAnotherStudent( ) + reRegister() - add(aStudent, aModule, aSemester, aSession) : void : Boolean : void : void Assessment - grade - semester - session - module - student : Char : int : Date : Module : Student + Assessment(aModule, aStudent, aSemester, aSession) + setGrade(aGrade) : Assessment : void Consider the use case 'record a grade for a student'. Discuss why the link class is now needed. © De Montfort University Page 76 Object Technology Lecture 1 Notes factors to be considered in design use cases drive all development navigability (one-way) one-way navigation between objects gives rise to the benefit of the simple maintenance of associations, especially when deleting objects, only one link has to be deleted navigability (two-way) two-way navigation between objects creates more complex maintenance of associations, especially when deleting objects this will also result in the increased speed of access and of processing of use cases link classes extra classes and objects are to be preferred only when needed try to support use cases with less complex coding, associations and memory visibility prefer private attributes and operations, try to encapsulate potentially dangerous operations that require pre-conditions think 'responsibilities' …. © De Montfort University Page 77 Object Technology Lecture 1 Notes Definitions and examples abstract An abstract class from which objects cannot be created (typically a generalisation high in the class hierarchy). abstraction The process of ignoring irrelevant details of a problem in order to concentrate on the most important parts. A bank customer has some accounts and an address but no height or weight. active line On a sequence diagram the lifeline is broadened to a double solid line when the object is active. actor A role played by an end user of a system; either a human, a hardware device or another system. A customer, a cash dispenser, the WWW. aCustomer aggregation The relationship that occurs when one class is made up of many occurrences of another class. Often described as the 'contains' relationship. A BankCustomerBase is an aggregation of all of the Customers. The AccountBase is an aggregation of all the BankAccounts, CurrentAccounts and SavingsAccounts. analysis An investigation to find out what the system requirements are of a problem. Not to be confused with attempting to describe how the system should be implemented. argument The value of a parameter. aPerson.setName(aName : String); the parameter is 'aName' aPerson.setName("Jane"); the value or argument is 'Jane' association A relationship between classes. An object of a class may have a link to an object of another class, each link is an instance of an association. A LoyaltyCard is owned by a Person. A BankAccount must be owned by a BankCustomer. attribute Describes the values of an object. A student is 21 years old. A student has an attribute 'age' set to the value 21. The state of this attribute will be 22 next year. All Students have an 'age'. behaviour The way an object reacts to a message. This reaction often depends upon the current state of an object. A bank account that is closed cannot be debited. 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. collaboration When a group of objects interact to complete a responsibility such as a use case. An object may issue a message to another object when completing its responsibilities. A bank is responsible for transferring money from one account to another. The two accounts collaborate with each other to check if they can be debited and credited. © De Montfort University Page 78 Object Technology Lecture 1 Notes collection A class of objects that is responsible for containing other objects. Different collection classes can often respond to the same messages - size( ), isEmpty( ), add(anObject), remove(anObject). Array, ArrayList, Vector, List composition The relationship that occurs when one class is made up of several others. Often described as the 'is-part-of' relationship. A Bank is a composition of its Customers (a BankCustomerBase) and their Accounts (an AccountBase). concrete A class from which instances may be created (typically a specialisation lower in the class hierarchy). constructor method A method of a class that is responsible for creating instances / objects of that class. Often the constructor is the same as the class name, starting with an uppercase letter. To make a person object use the method Person(aName,anAge,aGender). delegation An object that cannot complete a responsibility such as a use case issues a message to another object which becomes responsible for completing the use case. 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. design A description of how a system should be implemented. Not the investigation into finding out what the system requirements are of a problem. 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 and (public) operations - to manipulate the customers and accounts. A program wishing to modify the Bank data (the customers and accounts) may do so ONLY via the operations provided by the Bank class. extending A method in a subclass that calls the one with the same name in a superclass but then carries out additional behaviour. The toString method in CurrentAccount displays the overdraft limit and calls the toString BankAccount to display the balance and number details. generalisation / specialisation A generalisation/specialisation relationship is one in which classes have been identified to encapsulate common features (generalisation) or extend features (specialisation) guard condition If there is a guard condition on a sequence diagram the message is only sent if the guard condition evaluates to true. [isEmpty ] add(anObject) inheritance The mechanism by which more-specific elements incorporate the structure and behaviour of more-general elements. instance creation / instantiation An operation of a class that creates an instance - a realisation of the class known as an object. aCustomer, aSavingsAccount © De Montfort University Page 79 Object Technology Lecture 1 Notes interface (class) an interface shows only public operation signatures, no methods are implemented. Any class wishing to implement an interface must provide methods for all these operations but can provide additional public and private attributes and methods. lifeline On a sequence diagram a dashed vertical line is drawn from the object symbol to the point at which the object is destroyed. 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>.<methodName><parameter(s)> myFridge.setTemperature(2) method 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 setTemperature(int temperature) { if((temperature >= minTemp) && (temperature <= maxTemp)) this.temperature = temperature; } It is the method that implements the operation to set the temperature of a fridge. model A simplification of reality, created in order to gain a better understanding of the system being created. A banking system models people as customers. multiplicity The number of objects in each class that are allowed to participate in the association. A LoyaltyCard is owned by exactly one Person. A BankCustomer may own between 0 and 5 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. For a given Person it is not possible to find out anything about any card that might be owned. A LoyaltyCard may send messages to a Person 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 to send messages to find out the owner of an account from the account and also to identify the accounts owned by a customer from the customer. object / instance An object that belongs to a particular class. 'myFridge' could be a Fridge object with a capacity of 10 items, a temperature of 2 and containing Milk and Eggs, 'yourFridge' might be empty and at a temperature of 5 degrees © De Montfort University Page 80 Object Technology Lecture 1 Notes 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. Setting the temperature of a Fridge object to a specified value is defined as public void setTemperature(int temperature) which is an operation defined in the class Fridge to be applied to any instance of Fridge. over-riding A method in a subclass that replaces one with the same name in a superclass. 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. problem statement An attempt to describe the services required by the proposed system. a report, interviews with current users of the existing system, wish lists, … 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 toString() method delegates to the module to supply this information. scenario A use case may have many variants. A scenario is one 'instance' of a use case. use case 'register a new student' a successful scenario - a new student registered - confirmation an unsuccessful scenario - no student registered - error message! sequence diagram Illustrates the behaviour specified in a use case with the interactions shown in a time sequence. single inheritance A variation of inheritance in which a child may have only one parent. state Attributes have a value - their state. The outcome of a message received by an object may depend on the state of the receiving object. A bank account is 'frozen', it can be debited only when unfrozen. subclass In an inheritance relationship this is the specialisation of another (the parent) class. super In a inheritance relationship this is the generalisation of another (the child) class. type A term used to specify entities with common behaviour. Not to be confused with a class that is a software implementation with attributes and methods. general bank accounts UML The Unified Modelling language. A way of representing models produced during the development process. A modelling language is usually diagramatic but can be text based. use case The functionality that a system will offer from the user’s perspective a customer debits his savings account. debit an account © De Montfort University Page 81 Object Technology Lecture 1 Notes user The end user of a system, either an actor or another system. a customer, a cash dispenser, the WWW. 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 is a private attribute of an account and can be modified by other classes only by the public methods deposit, withdraw and transfer provided in the Bank class. whole-part associations There are two types of whole-part associations defined as 'aggregation' and 'composition'. © De Montfort University Page 82