chapter 3comp.mq.edu.au/books/rasd2ed/readersarea/lecturesli… · · 2008-12-07chapter 3.1...
TRANSCRIPT
MACIASZEK, L.A. (2005): Requirements Analysis and System Design, 2nd ed.
Addison Wesley, Harlow England, 504p.ISBN 0 321 20464 6
© Pearson Education Limited 2005
Chapter 3.1 Objects and Object Modeling
Fundamentals of Object Technology
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 22
TopicsTopicsFundamentals of object
technology
• Instance object
• Class
• Variables, methods, and
constructors
• Association
• Aggregation and composition
• Generalization and
inheritance
• Abstract class
• Interface
Fundamentals of object
modeling
• Use case modeling
• Activity modeling
• Class modeling
• Interaction modeling
• Statechart modeling
• Implementation models
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 33
Fundamentals of OTFundamentals of OT
Object has
• State
• Behavior
• Identity
(equal ≠ identical)
Objects and natural systems
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 44
Instance objectInstance objectClass• an abstraction (generic description) for a set of
objects• a class for objects (but better to avoid the term
“object class” because a class can be instantiated into an object – “object class object’ would sound a bit strange)
Instance object• an instance of a class• object, instance, but not object instance
Class object• an instantiated class (everything in an object
oriented system is an object)
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 55
Object notationObject notation
c1 : Course
course_number = COMP227course_name = Requirements Analysis and Systems Design
c1 : Course :Course c1
objectname: classname attributename: [type] = value
No compartment for operations in objects!Exception – prototypical (delegation-based) languages, such as Self or Newton
anonymous object classname suppressed
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 66
How do objects collaborate?How do objects collaborate? : Order
: Shipment : Stock
: Purchase
3. analyzeLevels( )1 . shipOrder(ord : Order)
2. getProducts(ord : Order)
4. reorder(prd : Product)
a role that many objects can play
a message invoking an operation on an object(numbers do not imply any sequence of execution)
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 77
How objects identify each other?How objects identify each other?object identifier - OID
Object longevity• Persistent object
–– outlives the execution of the programoutlives the execution of the program
–– swizzlingswizzling to convert persistent OID (disk address) to transient OID to convert persistent OID (disk address) to transient OID (memory address)(memory address)
• Transient object
c1 : Course
course_number = COMP227course_name = Requirements Analysis and Systems Designteacher: identity = TTT999
CCC888c1 : Course
course_number = COMP227course_name = Requirements Analysis and Systems Designteacher: identity = TTT999
CCC888
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 88
OIDs to implement associationsOIDs to implement associations
c1 : Course
course_number = COMP227course_name = Requirements Analysis and Systems Design
c2 : Course
t1 : Teacher
coursecourse
teacher
teacher
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 99
Transient linkTransient linkHow does an object know the OID of another object
if there is no persistent link?
• Previous access to an object still “memorized” in some
program variable
• Search on the database
• A “map” object that associates objects to other objects by
logical identifiers (primary keys) or similar means
• Creating a new object
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1010
Message passingMessage passingcrs_ref.getCourseName(out crs_name)
in, out, and in/out arguments• Most OO languages do not make such distinction explicit• In Java:
–– message arguments of primitive data types are passed by valuemessage arguments of primitive data types are passed by value• act as input arguments• the change of argument values not possible because the operation acts
on a copy of the argument
–– “pass by value” for non“pass by value” for non--primitive data types results in the operation primitive data types results in the operation receiving the reference of the argument, not its valuereceiving the reference of the argument, not its value
• the reference can be used to access and possibly modify the attribute values within the passed object
• the above eliminates the need for explicit in/out arguments
–– return type of an operation substitutes a need for explicit return type of an operation substitutes a need for explicit out out argumentsarguments
• operation can return only one return value or no value at all (void)• however, it can return non-primitive type (i.e. an object of any complexity)
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1111
Class, attributesClass, attributesClas s nam e
Attributes
Operations ()
Orderorder_number : Int egerorder_date : Dateorder_value : Currency
Coursecourse_number : Stringcourse_name : String
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1212
Attribute type designating a classAttribute type designating a classShipment
shipOrder(ord : Order)
OrderorderNumber : IntegerorderDate : DateorderValue : Currency theShipment
theOrder
ShipmenttheOrder : Order
shipOrder(ord : Order)
OrderorderNumber : IntegerorderDate : DateorderValue : CurrencytheShipment : Shipment
analysis model
implementation model
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1313
Attribute visibilityAttribute visibilityprivate attributes and public operationsoperations encapsulate attributes
Purchase- purchaseNumber : String- purchaseDate : Date- purchaseValue : Currency
+ reorder(prd : Product)
PurchasepurchaseNumber : StringpurchaseDate : DatepurchaseValue : Currency
reorder(prd : Product)
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1414
Operations in object collaborationOperations in object collaboration
Stock
getProducts(ord : Order) : CollectionanalyzeLevels()
Purchase
reorder(prd : Product)
Shipment
shipOrder(ord : Order)
Order Product
: Order
: Shipment : Stock
: Purchase
3. analyzeLevels( )1 . shipOrder(ord : Order)
2. getProducts(ord : Order)
4. reorder(prd : Product)
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1515
Operation, visibility, scope, class objectOperation, visibility, scope, class objectmethod – procedure that implements an operationmessage name = method namesignature = list of formal arguments of a methodvisibility ≠ scope• instance scope when operation invoked on instance
object (findEmpAge())• class scope when operation invoked on class object
(findAverageAge())Class object• most prog. lang. do not instantiate class object• they only provide a syntax to refer to the class name in
order to access a class-scope attribute or call a class-scope operation → static attribute/operation
Example → next slide
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1616
ClassClass--scope attributes and operations scope attributes and operations -- exampleexampleStudent
studentId : S tringstudentName : S tringnumberOfS tudents : intmaxCoursesPerSemester : int
<<static>> averageStudentAge() : double
public class Student {
private String studentId; //accessible via Student’s operations private String studentName; //accessible via Student’s operationsprivate static int numberOfStudents;//accessible only to Student’s static methods, such as averageStudentAge() public static int maxCoursesPerSemester; //accessible via Student:: maxCoursesPerSemester
public static double averageStudentAge() { implementation code here }//callable by referring to the class name – Student::averageStudentAge()//callable also with an object of the class – std.averageStudentAge()
}
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1717
Variables, methods, constructorsVariables, methods, constructorsVariable – name for a storage space• data member – variable declared in a class
–– instance variable (instance scope)instance variable (instance scope)–– class variable (class scope)class variable (class scope)
• local variable – variable declared in a method bodyMethod – implementation of an operation• method prototype = name + signature + return type• overloaded methods – same names, different signatures
Constructor• special “method” to instantiate objects of the class• constructor name = class name• constructor has no return type• class must have at least one constructor• invoked with the new keyword
Student std22 = new Student(); Student std22 = new Student(); //default constructor//default constructor
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1818
AssociationAssociation
ShipmentshipmentId : StringshipmentDate : Datecarrier : String
shipOrder(ord : Order)
OrderorderNumber : IntegerorderDate : DateorderValue : Currency
n
n
theShipment n
theOrder
n
OrdShip
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 1919
Association degreeAssociation degreeBinary
Unary (singular)
Ternary
Employee0..n
0..1
managerOf
0..n
managedBy
0..1
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2020
Association multiplicityAssociation multiplicity0..10..n1..11..nn
CourseOffering
Teacher
0..n
1..nteaches
0..n
taughtBy
1..n
0..n
1..1
isInChargeOf
0..n
isManagedBy
1..1
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2121
Association link and extentAssociation link and extentLink – association instance• represents a rolename• can be a collection of references
Extent – set of association instances• in the figure, the extend of the association is five (five links)
Order 1Shipment 1
Shipment 2
Shipment 2Order 2
Link 1 with
3 references
Link 2
Link 3
Link 5
Order 1Shipment 1
Shipment 2
Shipment 3Order 2
Link 1 with
3 references
Link 4with
2 references
Link 2
Link 3
Link 5
Order 1Shipment 1
Shipment 2
Shipment 2Order 2
Link 1 with
3 references
Link 2
Link 3
Link 5
Order 1Shipment 1
Shipment 2
Shipment 3Order 2
Link 1 with
3 references
Link 4with
2 references
Link 2
Link 3
Link 5Link 5
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2222
Association classAssociation class
Assessmentmark : List(Number)totalMark : Numbergrade : Byte
StudentCourseOffering
nn nn
Parameterized type
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2323
Composition and aggregationComposition and aggregationComposition –aggregation by valueAggregation –aggregation by referenceProperties:• Transitivity• Asymmetry• Existence
dependency
Implemented by buried references or inner classes → next slides
Book
Chapter
n
is_part_of
hasn
Sectionnn
Crate
BeerBottle
nn
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2424
Implementing aggregation by buried referenceImplementing aggregation by buried reference
public class Book {
private String title;private Chapter theChapter[];private TableOfContents theTableOfContents;public Book() {//default constructor }public boolean search(String what) {return true;}
}
Chaptertext : Textfigure : Graphics
search(what : String) : booleanChapter()
Booktitle : String
search(what : String) : booleanBook()
n
TableOfContents
generate() : VoidTableOfContents()
1n
1
-theBook
-theChapter -theTableOfContents
-theBook
not different to associationby means of variable with private visibilityhowever, in Java, classes cannot have private visibility
• subset classes must have public or package visibility
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2525
Implementing aggregation by inner classesImplementing aggregation by inner classespublic class Book {
private String title;private Chapter[] ch;private TableOfContents toc;public Book(...) { ...
toc = new TableOfContents();ch = new Chapter[numberChapters];for (int i=0; i<numberChapters; i++)
ch[i] = new Chapter();}public Void displayToc(){
toc.generate();return;
}private class TableOfContents
{private Void generate() {...}
}}
TableOfContents
generate() : VoidTableOfContents()
<<inner>>
Booktitle : S tring
displayToc() : Voidsearch(what : S tring) : booleanBook()
1-toc 1
Chaptertext : Textfigure[ ] : Graphics
search(what : String) : booleanChapter(chNum : int)
<<inner>>
n-ch n
inner class can be private (accessible
only from outer class)
outer class instantiates inner objects in its own constructor
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2626
GeneralizationGeneralizationPerson
fullName : StringdateOfBirth : java.util.Date
age() : intgetYear() : intgetYear(date : java.util.Date) : intPerson()
EmployeedateHired : java.util.Datesalary : intleaveEntitlement : intleaveTaken : int
remainingLeave() : intEmployee()
public class Person{
private String fullName;private Date dateOfBirth;public Person(){...}public int age(){
return getYear() - getYear(dateOfBirth);}
}
public class Employee extends Person{
private Date dateHired;private int salary;private int leaveEntitlement;private int leaveTaken;public Employee(){...}public int remainingLeave(){
return leaveEntitlement - leaveTaken;}
}
A subclass inherits the structure and behavior of its superclass
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2727
PersonfullName : StringdateOfBirth : java.util.Date
age() : intPerson()
EmployeedateHired : java.util.Datesalary : intleaveEntitlement : intleaveTaken : int
remainingLeave() : intEmployee()
ManagerdateAppointed : java.util.DateleaveSupplement : int
remainingLeave() : intManager()
PolymorphismPolymorphism
The same signature(operation name and the number and type of arguments)
public class Manager extends Employee {
private Date dateAppointed;private int leaveSupplement;public Manager() {...}public int remainingLeave() {int mrl;mrl = super.remainingLeave() + leaveSupplement;return mrl;
}}
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2828
Multiple inheritanceMultiple inheritancePerson
fullName : StringdateOfBirth : Date
age() : Integer
Teacher S tudent
Tutor
PostgraduateStudent
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 2929
Multiple classificationMultiple classificationMultiple inheritance• A class may have many
superclasses, but a single class must be defined for each object
Multiple classification• An object is
simultaneously the instance of two or more classes
The problem arises if The problem arises if PersonPerson is specialized in few orthogonal is specialized in few orthogonal hierarchies hierarchies
PersonPerson can be can be EmployeeEmployee or or StudentStudent, , MaleMale or or FemaleFemale, , ChildChild or or AdultAdult, etc. , etc.
Without multiple classificationWithout multiple classificationneed to define classes for each legal combination between need to define classes for each legal combination between the orthogonal hierarchies the orthogonal hierarchies ChildFemaleStudentChildFemaleStudent etc.etc.
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3030
Dynamic classificationDynamic classificationAn object does not only belong to multiple classes but it can gain or lose classes over its lifetimeA Person object can be just an employee one day and a manager (and employee) another dayIn most current object-oriented programming environments, an object cannot change its class after it has been instantiated (created)
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3131
Abstract classAbstract classParent class that will not have direct instance objectsAbstract class cannot instantiate objects because it has at least one abstract operation
public abstract class VideoMedium{
public abstract Double rentalCharge();}
public class VideoDisk extends VideoMedium{
public VideoDisk() {...}public Double rentalCharge() {return null;
}}
VideoMedium
rentalCharge() : Double
V ideoTape
V ideoTape()renta lCharge() : Double
VideoDisk
VideoDisk()rentalCharge() : Double
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3232
Interface Interface vsvs abstract classabstract classInterface – a definition of a semantic type with attributes (constants only) and operations but without actual declarations (implementations) of operations• classes that implement the interface provide the declarations
Abstract class has undesirable effect of the fragile base class problemUnlike abstract classes• interfaces are helpful for modeling situations that ask for multiple
inheritance• interface does not implement (even partially) any of its methods
–– but still, but still, pure abstract class pure abstract class ≠≠ interfaceinterface• in case of interface, any class in the system can implement it, not just the
subclasses• a class can implement any number of interfaces
• interface defines a reference type that separates client objects from the implementation changes in the supplier objects
–– the implementation of the interface can change and the client obthe implementation of the interface can change and the client object ject may not be affectedmay not be affected
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3333
Multiple implementation inheritance not allowed in JavaMultiple implementation inheritance not allowed in Java
VideoMedium
rentalCharge() : Double
VideoTape
VideoTape()rentalCharge() : Double
VideoDisk
VideoDisk()rentalCharge() : Double
VideoPlayer
VideoEquipmentpurchasePrice : DoubledateOfPurchase : java.sql.Date
VideoCamera
Not allowed in Java!
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3434
Implementing Java interfaceImplementing Java interface
VideoMedium
rentalCharge() : Double
VideoTape
VideoTape()rentalCharge() : Double
V ideoDisk
VideoDisk()rentalCharge() : Double
V ideoPlayer
V ideoP layer()renta lCharge() : Double
SoundSystem
VideoEquipmentpurchasePrice : DoubledateOfPurchase : java.sql.Date
VideoCamera
public interface VideoMedium{
Double rentalCharge();}
public class VideoPlayerextends VideoEquipmentimplements VideoMedium
{public VideoPlayer() {...}public Double rentalCharge() {return null;
}}
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3535
Using interface to eliminate dependency to supplierUsing interface to eliminate dependency to supplier
VideoTape
VideoTape()rentalCharge() : Double
V ideoDisk
VideoDisk()rentalCharge() : Double
V ideoPlayer
V ideoP layer()renta lCharge() : Double
SoundSystem
VideoEquipmentpurchasePrice : DoubledateOfPurchase : java.sql.Date
VideoCamera
ChargeCalculator
getRentalCharge() : DoubleChargeCalculator()
VideoMedium
rentalCharge() : Double
theVideo
<<uses>>
public class ChargeCalculator{
VideoMedium theVideo;public Double getRentalCharge() {return theVideo.rentalCharge();
}}
© Pearson Education 2005© Pearson Education 2005 Chapter 3.1 (Maciaszek Chapter 3.1 (Maciaszek -- RASD 2/e)RASD 2/e) 3636
SummarySummaryEach object has a state, behavior and identityThere are instance objects and class objectsClass defines attributes and operationsThere are three kinds of relationships –association, aggregation, generalizationGeneralization provides the basis for polymorphism and inheritanceCommercial programming environments support multiple inheritance directly (C++, C#) or by means of interfaces (Java)Multiple and dynamic classification is still not supported commerciallyAbstract classes and interfaces are important in modeling