CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
1
CIS225 – Advanced Java
Introduction to Object-Introduction to Object-Oriented Analysis and Oriented Analysis and
Design Design
Introduction
This presentation introduces objects, classes, This presentation introduces objects, classes, class inheritance and interfaces. class inheritance and interfaces.
You will learn the concepts of object-You will learn the concepts of object-oriented programming. Heavy emphasis is oriented programming. Heavy emphasis is placed on the development of software placed on the development of software systems using the Object-Oriented Paradigmsystems using the Object-Oriented Paradigm
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
2
IntroductionThe key to object-oriented programming is to The key to object-oriented programming is to model the application in terms of cooperative model the application in terms of cooperative objects that reflect reality. objects that reflect reality.
You design classes that describe the behavior You design classes that describe the behavior of these objects. Carefully designed classes of these objects. Carefully designed classes are the key to a successful application. are the key to a successful application.
There are many levels of abstractions in There are many levels of abstractions in system design: method abstraction, class system design: method abstraction, class abstraction, encapsulation, etc abstraction, encapsulation, etc
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
3
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
4
Overview The Object-Oriented ParadigmThe Object-Oriented Paradigm Managing Complexity with AbstractionManaging Complexity with Abstraction Building a Specification ModelBuilding a Specification Model Finding Objects and Identifying Finding Objects and Identifying
ResponsibilitiesResponsibilities Specifying Static and Dynamic BehaviorSpecifying Static and Dynamic Behavior Introduction to the Unified Modeling Introduction to the Unified Modeling
LanguageLanguage Introduction to Design PatternsIntroduction to Design Patterns SummarySummary
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
5
The Object-Oriented Paradigmis defined as a “set of theories, standards, and methods that together represent a way of organizing knowledge
Benefits of O-O TechnologyReduces the cost of software development:Reduces the cost of software development:
• Provides the software developer with real- Provides the software developer with real- world, programmable componentsworld, programmable components
• Provides the capability Provides the capability to share and reuse to share and reuse code code with O-O techniques that reduce time to with O-O techniques that reduce time to develop applicationsdevelop applications
• For example: to create a button, you simply use For example: to create a button, you simply use the JButton class to create the instance of the JButton class to create the instance of JButton - don’t reinvent the wheelJButton - don’t reinvent the wheel
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
6
Benefits of O-O Technology cont.Reduces the cost of software development:Reduces the cost of software development:
• Provides the capability to localize and Provides the capability to localize and minimize the effects of modifications through minimize the effects of modifications through programming abstraction mechanisms for programming abstraction mechanisms for faster enhancement development and provides faster enhancement development and provides more reliable and robust softwaremore reliable and robust software
• Manages complexity allow developers to Manages complexity allow developers to address more difficult applicationsaddress more difficult applications
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
7
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
8
Managing Complexity with Abstraction History
In the early 1960’s, developers had two major constraints : •Performance limited in processor speed the average desktop computer of today is faster than the largest machines of the60s
•Using less core(memory) and storage capacity-virtual memory had not been invented.
HistoryHistory(cont.) The programming language that we use directly The programming language that we use directly
influence the way that we view (model) reality.influence the way that we view (model) reality.
In the 1970s, we used the imperative programming In the 1970s, we used the imperative programming paradigm for modeling reality-paradigm for modeling reality-
C, Pascal, and PL/1 – the structured methodC, Pascal, and PL/1 – the structured method
high degree of coupling, and poor cohesionhigh degree of coupling, and poor cohesion
In the 1980s, we used SQL and 4GL with relational In the 1980s, we used SQL and 4GL with relational databases. We used a data-modeling paradigm databases. We used a data-modeling paradigm entity-relationship diagrams entity-relationship diagrams
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
9
History(cont.) In the 1990s, we used C++, Smalltalk, and Objective In the 1990s, we used C++, Smalltalk, and Objective
C -object-oriented (O-O) paradigm for modeling C -object-oriented (O-O) paradigm for modeling reality-reality-
The object-orientation paradigm using these The object-orientation paradigm using these languages had many limitations – high cohesion, languages had many limitations – high cohesion, tight couplingtight coupling
Java now provides us with a refined version of the Java now provides us with a refined version of the O-O paradigm. We have added a few new keywords O-O paradigm. We have added a few new keywords and additional features and data types. and additional features and data types.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
10
History(cont.) Most importantly, programmers now have add a Most importantly, programmers now have add a
modeling mechanism to view and model reality. modeling mechanism to view and model reality.
Think what it means to computeThink what it means to compute How we organize our information inside a computer How we organize our information inside a computer
systemsystem How we describe our view (model) of realityHow we describe our view (model) of reality
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
11
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
12
The Object-Oriented Paradigm cont.
Classes and ObjectsClasses and Objects Object-Oriented PrinciplesObject-Oriented Principles OO Model of ComputationOO Model of Computation
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
13
Classes A class can be viewed from four A class can be viewed from four
different perspectives: different perspectives: Modeling Modeling Design Design Implementation Implementation CompilationCompilation
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
14
Classes
The The classclass is the essential Java is the essential Java construct.construct.
A class is a template or blueprint A class is a template or blueprint for objects. To program in Java, you for objects. To program in Java, you must understand classes and be able must understand classes and be able to write and use them. to write and use them.
.A program is defined by using one .A program is defined by using one
or more classes.or more classes.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
15
Classes - From a modeling perspective a class is a template for a a class is a template for a category category and defines:and defines:
1.1. CharacteristicsCharacteristics (attributes) - data variables (attributes) - data variables
2.2. ServicesServices (behaviors) - methods (behaviors) - methodsIts Its interfaceinterface is the protocols used to access an object’s is the protocols used to access an object’s
services and its internal stateservices and its internal stateIts Its implementationimplementation are the internal procedures for are the internal procedures for
providing servicesproviding services
3.3. RulesRules and and PoliciesPolicies – constraints that are applied – constraints that are applied
4.4. RelationshipsRelationships – peer-to-peer, hierarchical, – peer-to-peer, hierarchical, generalization/specializationgeneralization/specialization
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
16
Classes- From a design perspective a class is a special kind of objecta class is a special kind of object It is a collection of all the objects instantiated It is a collection of all the objects instantiated
from itfrom it It is used to create and destroy objects that It is used to create and destroy objects that
belong to its collectionbelong to its collection It is used to hold common data and provide It is used to hold common data and provide
for group services such as:for group services such as: Find an instanceFind an instance Keep averagesKeep averages Hold shared informationHold shared information
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
17
Classes -From an implementation perspective a class is a “global” object with class data a class is a “global” object with class data
members and class servicesmembers and class services Applications can access the class services Applications can access the class services
by using the class’ nameby using the class’ name
An application can create objects by using An application can create objects by using its constructor to “instantiate” an object its constructor to “instantiate” an object
A class is used to implement the category A class is used to implement the category concept in the Java programming languageconcept in the Java programming language
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
18
Classes -From a compiler’s perspective the class is a programmer’s defined data typethe class is a programmer’s defined data type
It is a mechanism for defining and creating It is a mechanism for defining and creating runtime objectsruntime objects
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
19
The 13 O-O Basic Principles1.1. EncapsulationEncapsulation
The object contains both the data and the code to The object contains both the data and the code to manipulate the data. A black box provides manipulate the data. A black box provides encapsulation the hiding of unimportant detailsencapsulation the hiding of unimportant details
2.2. Information HidingInformation Hiding The object that contains the data defines the The object that contains the data defines the
services available to other objects and hides the services available to other objects and hides the data and implementation detailsdata and implementation details
3.3. MessageMessage PassingPassing An object may communicate with another object An object may communicate with another object
only by exchanging messages (parameters)only by exchanging messages (parameters)
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
20
The 13 O-O Basic Principles(cont.)
4. Late Binding4. Late Binding The specific receiver of any given message is not The specific receiver of any given message is not
known known until until runtime.runtime. So the determination of which So the determination of which method method to to invokeinvoke cannot be made until cannot be made until run timerun time. .
The virtual machine, not the compiler, selects the The virtual machine, not the compiler, selects the appropriate method.appropriate method.
Late binding enables us to model a real behavior of the Late binding enables us to model a real behavior of the world –world –
Example: when a class is scheduled, it is unknown Example: when a class is scheduled, it is unknown who will attend or how many students. You only who will attend or how many students. You only know once the class begins. Gen/Spec with know once the class begins. Gen/Spec with polymorphism (#8) principlepolymorphism (#8) principle
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
21
The 13 O-O Basic Principles(cont.) 5. 5. DelegationDelegation
Work is passed via message-passing from one object Work is passed via message-passing from one object (client) to another object (agent) until it finally reaches (client) to another object (agent) until it finally reaches the object that has both the data and code to perform the object that has both the data and code to perform the work –the work –
can delegate the authority to get the work done; cannot can delegate the authority to get the work done; cannot delegate the responsibility -an example of information delegate the responsibility -an example of information hiding principlehiding principle
Delegation is sometimes called the perfect bureaucratic Delegation is sometimes called the perfect bureaucratic principleprinciple
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
22
The 13 O-O Basic Principles(cont.)
6. Class/Instance/Object 6. Class/Instance/Object
Categorizing helps us to organize the complex Categorizing helps us to organize the complex world in which we live.world in which we live.
All objects are instances of a class and can be All objects are instances of a class and can be
created or deleted at runtimecreated or deleted at runtime
How an object provides a service is determineHow an object provides a service is determineby the class of which the object is an instanceby the class of which the object is an instance
Thus, all objects of the same class, use the same Thus, all objects of the same class, use the same method (code) in response to a specific service method (code) in response to a specific service requestrequest
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
23
The 13 O-O Principles cont.7. 7. Generalization/Specialization without Generalization/Specialization without
PolymorphismPolymorphism Classes can be organized by using a Classes can be organized by using a
hierarchical inheritance structurehierarchical inheritance structure
In the structure, the specialized class (subclass) In the structure, the specialized class (subclass) inherits the state (data fields), the behavior (set of inherits the state (data fields), the behavior (set of methods), and the relationships from the methods), and the relationships from the superclasssuperclass
An An abstract superclass abstract superclass is a class that is used is a class that is used to create only subclasses: therefore there are no to create only subclasses: therefore there are no direct instances of that class.direct instances of that class.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
24
Abstract Class (contd.)
Abstract classes are like regular classes with data and methods, but you cannot create instances (objects) of abstract classes using the new operator.
An abstract method cannot be placed in a nonabstract class.
If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
25
Abstract Class (contd.)
A classes that contains abstract methods must be abstract. However, it is possible to declare an abstract class that contains no abstract methods.
A subclass can be abstract even if its superclass is concrete.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
26
The 13 O-O Principles cont.8. Generalization/Specialization with 8. Generalization/Specialization with
PolymorphismPolymorphism The subclass inherits the attributes, The subclass inherits the attributes,
relationships, prototype, and methods relationships, prototype, and methods from the superclass that is higher in the from the superclass that is higher in the tree.tree.
Subclasses can create their own method Subclasses can create their own method to override behavior from the superclass to override behavior from the superclass to provide the same service.to provide the same service.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
27
The 13 O-O Principles
9. Relationships9. Relationships Associations and aggregation are used to Associations and aggregation are used to
capture the collaboration between objects capture the collaboration between objects necessary to provide a service to a client - necessary to provide a service to a client - called a called a linklink
Types of relationships include: association, Types of relationships include: association, aggregation, composition, link, aggregation, composition, link, generalization, specializationgeneralization, specialization
will discuss later with exampleswill discuss later with examples
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
28
The 13 O-O Principles cont
The The instanceofinstanceof operator can help us learn the class of an operator can help us learn the class of an object.object.
Student x = new UndergraduateStudentStudent x = new UndergraduateStudent();();if(x instanceof UndergraduateStudent ){if(x instanceof UndergraduateStudent ){
System.out.println(“Mr. X is an System.out.println(“Mr. X is an undergraduate student”);undergraduate student”);
}else{}else{
System.out.println(“Mr. X System.out.println(“Mr. X is a is a graduate graduate
student”);student”);
}}
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
29
The 13 O-O Principles cont 10. Interface/Instance/Object10. Interface/Instance/Object
All objects that implement an interface are All objects that implement an interface are instances of that interfaceinstances of that interface
Interfaces define Interfaces define typestypes
Instances of an interface cannot be created Instances of an interface cannot be created (instantiated) or destroyed (deleted) as an (instantiated) or destroyed (deleted) as an instance interface.instance interface.
Each must be created or destroyed as an Each must be created or destroyed as an instance of the class to which it is a member.instance of the class to which it is a member.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
30
The 13 O-O Principles cont
11. Generalization/Specialization of 11. Generalization/Specialization of InterfacesInterfacesInterfaces can be organized by using a Interfaces can be organized by using a
hierarchical inheritance structurehierarchical inheritance structure
The specialized interface inherits the service The specialized interface inherits the service protocol from the generalized interfaces that protocol from the generalized interfaces that are higher in the (tree) structure.are higher in the (tree) structure.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
31
The 13 O-O Principles cont
12. Reflection12. Reflection Each object knows detailed information Each object knows detailed information
about the classes and interfaces of which about the classes and interfaces of which it is an instanceit is an instance
This means that an application can at This means that an application can at runtime acquire detail information about runtime acquire detail information about the object from the object itself.the object from the object itself.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
32
The 13 O-O Principles cont 12. Reflection cont’d. ways:12. Reflection cont’d. ways:
1. Determine the class of the object1. Determine the class of the object
2. Get info about a class’s modifiers, member 2. Get info about a class’s modifiers, member variables, methods, constructors, and variables, methods, constructors, and superclasssuperclass
3. Find out what constants and method 3. Find out what constants and method declarations belong to an interfacedeclarations belong to an interface
4. Create an instance of a class whose name is not 4. Create an instance of a class whose name is not known until runtimeknown until runtime
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
33
The 13 O-O Principles cont 12. Reflection cont’d. ways:12. Reflection cont’d. ways:
5. Get and set the value of an object’s field , even 5. Get and set the value of an object’s field , even if the field name is not known to your if the field name is not known to your program until run time.program until run time.
6. Invoke a method on an object, even if the 6. Invoke a method on an object, even if the method is not known until runtime.method is not known until runtime.
7. Create a new array, whose size and component 7. Create a new array, whose size and component type are not known until runtime, and then type are not known until runtime, and then modify the array’s components.modify the array’s components.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
34
The 13 O-O Principles cont 12. Reflection cont’d. 12. Reflection cont’d.
To make your programs easier to debug and To make your programs easier to debug and maintain do not use Method objects.maintain do not use Method objects.
Instead use interfaces and then implement themInstead use interfaces and then implement them in the class that performs the needed actionin the class that performs the needed action
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
35
The 13 O-O Principles cont
13. Multithreading13. Multithreading Each object can have concurrent Each object can have concurrent
execution pathsexecution paths
This means that an object can handle This means that an object can handle multiple events (or service requests) in a multiple events (or service requests) in a concurrent manner)concurrent manner)
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
36
RefactoringMartin Fowler coined this term for restructuring code in aDisciplined way –make small transformation to your code
Example (From):
Car Shape
selected
setSelectedisSelected
HouseShape
selected
setSelected
isSelected
SelectableShape
selected
setSelectedisSelected
CarShape HouseShape
To:
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
37
O-O Paradigm -Objects An object is the most fundamental An object is the most fundamental
concept/mechanism of O-O programmingconcept/mechanism of O-O programming There are three different ways of looking There are three different ways of looking
at objects:at objects:Application modeling viewApplication modeling viewDesign modeling viewDesign modeling viewFormal viewpointFormal viewpoint
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
38
Objects - From an application modeling
view An object has the following components:An object has the following components:
1.1. CharacteristicsCharacteristics – internal information that describes – internal information that describes the object (attribute name and value)the object (attribute name and value)
2.2. ServicesServices (behaviors)– a collection of services that has (behaviors)– a collection of services that has some semantic meaning sometimes called a protocol some semantic meaning sometimes called a protocol
a. interface (prototype internal information)a. interface (prototype internal information) b. implementation (method)b. implementation (method)
33. Unique Identifier. Unique Identifier – Each object is given a unique ID – Each object is given a unique ID at creation and cannot be changed. Usually the at creation and cannot be changed. Usually the machine id number plus the time in milliseconds - machine id number plus the time in milliseconds -
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
39
Objects - From an application modeling view cont.
An object has the following components:An object has the following components:4. Rules and Policies4. Rules and Policies – establish constraints – establish constraints
which are applied to the objectwhich are applied to the object
5. Relationships5. Relationships – how objects stand in relations – how objects stand in relations with other objects peer-to-peer or hierarchicalwith other objects peer-to-peer or hierarchical
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
40
Objects From a From a design modelingdesign modeling view an object: view an object:
1.1. Is an example (instance) of a Is an example (instance) of a categorycategory (class) form a hierarchy of gen/spec(class) form a hierarchy of gen/spec
2.2. May be an example of a May be an example of a typetype (interface) (interface) A type is a collection of service declaration A type is a collection of service declaration
(service name, arguments, return type and (service name, arguments, return type and exception thrown) with no implementation codeexception thrown) with no implementation code
3. May be a “3. May be a “metaclassmetaclass” object- may have ” object- may have attributes, services, object relationships, and attributes, services, object relationships, and rules; however may not be in a gen/spec rules; however may not be in a gen/spec relationshiprelationship
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
41
Objects From a From a design modelingdesign modeling view an object view an object
cont. :cont. :4. Is created by a category (class) object4. Is created by a category (class) object
5. Can communicate either 5. Can communicate either synchronoussynchronous (method invocation) or (method invocation) or asynchronousasynchronous (event generation) with other objects(event generation) with other objects
6. Can be “6. Can be “persistentlypersistently” associated with ” associated with another object in either a peer-to-peer or another object in either a peer-to-peer or hierarchical relationshiphierarchical relationship
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
42
Objects From a From a formalformal perspective an object is defined by: perspective an object is defined by:
Its Its responsibilitiesresponsibilities – the value that it adds to the – the value that it adds to the systemsystem
Its Its rule setrule set – – -Attribute Assertions: Range, Enumeration, -Attribute Assertions: Range, Enumeration, and Type constraintsand Type constraints - Operation Assertions: Pre- and Post- and- Operation Assertions: Pre- and Post- and invariance conditionsinvariance conditions - Class invariance: A logical statement(s) - Class invariance: A logical statement(s) about the object that must be true at all about the object that must be true at all timestimes
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
43
Objects cont. From a From a formalformal perspective an object is defined by: perspective an object is defined by:
Its Its rule rule setset(cont’d)(cont’d):: - inference engines –resolve multiple - inference engines –resolve multiple inheritance conflictsinheritance conflicts Its Its classification –classification –must be in some category must be in some category
(class) even if it is a category of one object(class) even if it is a category of one object
Its Its type(s). type(s). An object may implement the An object may implement the services of any specific type w/o being services of any specific type w/o being constrained it its implementation of the servicesconstrained it its implementation of the services
Its Its relationshipsrelationships with other objects peer-to-peer with other objects peer-to-peer or hierarchicalor hierarchical
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
44
OO Model of Computation The problem-solving view of OO The problem-solving view of OO
programming is different from the programming is different from the pigeonhole modelpigeonhole model used with used with imperative programmingimperative programming
OO use terms like OO use terms like objectobject, , classclass, and , and servicesservices instead of terms like instead of terms like assignmentsassignments, , variablesvariables or or memorymemory addressesaddresses
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
45
OO Model of Computation OO uses a OO uses a community of helperscommunity of helpers that that
work together to solve the problemwork together to solve the problem OO programming uses a OO programming uses a simulation simulation
modelmodel of computation of computationWe define objects in the problem We define objects in the problem
domain that will help us solve the domain that will help us solve the problem problem
We define how these objects interact We define how these objects interact with one another and then set them with one another and then set them in motionin motion
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
46
Managing Complexity with Abstraction
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
47
Managing Complexity with Abstraction
Complex SystemsComplex Systems Abstraction MechanismsAbstraction Mechanisms Service Activation AbstractionsService Activation Abstractions Process Control AbstractionsProcess Control Abstractions RelationshipsRelationships RulesRules
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
48
Complex Systems
Much of the complexity of imperative Much of the complexity of imperative programming stems from the high degree of programming stems from the high degree of coupling and poor cohesion makes the coupling and poor cohesion makes the systems inflexible and unmaintainablesystems inflexible and unmaintainable
CouplingCoupling – the dependence of one piece – the dependence of one piece of code on either another section of code of code on either another section of code and/or some data storageand/or some data storage
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
49
Complex Systems
CohesionCohesion – how well a set of code and its – how well a set of code and its
associated data fit togetherassociated data fit together
A class should describe a single entity, and all the A class should describe a single entity, and all the class operations (methods) should fit together to class operations (methods) should fit together to support a coherent purposesupport a coherent purpose
We can use a class for students. We should We can use a class for students. We should not not include student and staff in the same class because include student and staff in the same class because students and staff have different entities.students and staff have different entities.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
50
Complex Systems Consistency
Follow standard Java programming style Follow standard Java programming style and naming conventions.and naming conventions.
Choose informative names for classes, data Choose informative names for classes, data fields, and methodsfields, and methods
A popular style is to place the data declaration A popular style is to place the data declaration before the constructor, and place constructors before the constructor, and place constructors before methods. See UML Class and Object before methods. See UML Class and Object diagram.doc in folder UML Folderdiagram.doc in folder UML Folder
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
51
Complex Systems Complex systems tend to have five key attributes:Complex systems tend to have five key attributes:
1.1. Complex systems take on the form of a hierarchyComplex systems take on the form of a hierarchy2.2. The choice of which system components are The choice of which system components are
considered primitive is arbitraryconsidered primitive is arbitrary3.3. Intracomponent links are usually stronger than Intracomponent links are usually stronger than
intercomponent linksintercomponent links4.4. Hierarchical systems are usually composed of a few Hierarchical systems are usually composed of a few
different kinds of subsystems combined or arranged in different kinds of subsystems combined or arranged in various ways various ways
5.5. A good complex system has usually evolved from a A good complex system has usually evolved from a good simple systemgood simple system
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
52
System Development is modeling The development of a large system is a The development of a large system is a modeling modeling
activity activity in which a series of increasingly detailed in which a series of increasingly detailed models is developedmodels is developed
The different types of models include:The different types of models include: Specification modelSpecification model – a black box model of – a black box model of
the system in terms of business value provided the system in terms of business value provided by itby it
Analysis modelAnalysis model – a model that demonstrates – a model that demonstrates how the specification model will be realizedhow the specification model will be realized
Design modelDesign model – a description of how the – a description of how the analysis model will be codedanalysis model will be coded
Code modelCode model – an implementation of the design – an implementation of the design model which upon compilation and execution model which upon compilation and execution provides a solution to the business problem.provides a solution to the business problem.
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
53
System Development
There are different software development There are different software development processes that can be used to control the processes that can be used to control the activities and level of detail while activities and level of detail while developing complex systemsdeveloping complex systems Waterfall process modelWaterfall process model Iterative process modelIterative process model Divide-and-Conquer (Functional Divide-and-Conquer (Functional
Decomposition)Decomposition) The Object-oriented approachThe Object-oriented approach
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
54
System Development cont.
Waterfall process modelWaterfall process model develops each system model develops each system model sequentially and describes the latersequentially and describes the later activities associated with testing, activities associated with testing, delivery , and maintenance. Each delivery , and maintenance. Each phase is completed before any workphase is completed before any work is started on the next phase. is started on the next phase.
Iterative process model (rapid Iterative process model (rapid programming) programming) iteratively develop all of the iteratively develop all of the models cycling through the phases models cycling through the phases
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
55
System Development cont.
Divide-and-Conquer (Functional Divide-and-Conquer (Functional
Decomposition)Decomposition) Take a big problem and break it into a number Take a big problem and break it into a number
of smaller problems of smaller problems
The Object-oriented approachThe Object-oriented approach Breaks a complex system into component Breaks a complex system into component parts in the form of objects and the parts in the form of objects and the relationships among themrelationships among them
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
56
Abstraction Mechanisms The history of software development is marked by the The history of software development is marked by the
introduction of successively more abstract mechanisms that introduction of successively more abstract mechanisms that give developers better tools to manage complexity. These give developers better tools to manage complexity. These include:include:Type abstractionsType abstractionsService activation abstractionsService activation abstractionsProcessing control abstractionsProcessing control abstractionsRelationships abstractionsRelationships abstractionsBehaviorsBehaviorsRulesRules
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
57
Type Abstractions Object-oriented abstraction mechanisms are Object-oriented abstraction mechanisms are
a natural progression of abstracting from a natural progression of abstracting from functions and simple data types to modules functions and simple data types to modules and abstract data types and then to objectsand abstract data types and then to objects
The concept of an object is the merging of The concept of an object is the merging of two separate concepts: data types and two separate concepts: data types and functions functions
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
58
Evolution of Data Abstraction
Basic Data Types Functions
ModulesAbstract Data Types (ADT)
Objects (instances)
Class (category)
Class with Gen/Spec (inheritance)
Polymorphism (overriding, overloading)
Interface (type)
Class with Reflection (RTTI)
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
59
Abstractions Mechanisms -Basic Data Types Early assembly language programmers had Early assembly language programmers had
only very basic data types- basic integer, only very basic data types- basic integer, floating point number, and character were floating point number, and character were the core data typethe core data type
Early programming language Early programming language extended extended the core set to include arrays the core set to include arrays and extended precision versions of these and extended precision versions of these data typesdata types
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
60
Type Abstractions Basic data typesBasic data types Abstract data typesAbstract data types FunctionsFunctions ModulesModules ObjectsObjects ClassClass Class with generalization/specializationClass with generalization/specialization PolymorphismPolymorphism InterfaceInterface ReflectionReflection
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
61
Service Activation Abstractions Abstractions that identify the mechanisms by which Abstractions that identify the mechanisms by which
data processing is activated to achieve business valuedata processing is activated to achieve business valueFunction CallFunction CallEvent ProcessingEvent Processing (Asynchronous (Asynchronous
communication)communication)Message PassingMessage Passing (Synchronous (Synchronous
communication)communication)SubscriptionSubscription (Asynchronous communication) (Asynchronous communication)
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
62
Processing Control Abstractions There are several traditional processing There are several traditional processing
control abstractions that have been control abstractions that have been incorporated into object-oriented approaches:incorporated into object-oriented approaches:Single Program ExecutionSingle Program ExecutionMultitaskingMultitaskingSequential ExecutionSequential ExecutionMultithreadingMultithreading
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
63
Relationships Prior to the introduction of the object and class Prior to the introduction of the object and class
abstractions, it was very difficult to capture abstractions, it was very difficult to capture information about the relationships between data information about the relationships between data itemsitems Generalization/specializationGeneralization/specialization (gen/spec) is a (gen/spec) is a
relationship between relationship between classesclasses AssociationsAssociations and and aggregationsaggregations are relationships are relationships
between between objectsobjects Behavior Behavior relationships permit both classes and relationships permit both classes and
objects to be organized using either gen/spec or objects to be organized using either gen/spec or association and aggregationassociation and aggregation
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
64
Association Describes a group of links with common structure Describes a group of links with common structure
and semanticsand semantics Common semantics implies that the services provided Common semantics implies that the services provided
by each object in the same class are the same, but they by each object in the same class are the same, but they may be polymorphicmay be polymorphic
All links in an association must connect objects All links in an association must connect objects from the same class to objects from a second classfrom the same class to objects from a second class
Associations are bidirectional and may be binary, Associations are bidirectional and may be binary, ternary, or higherternary, or higher
Association is a “weak” relationshipAssociation is a “weak” relationship
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
65
Association Association represents a general binary Association represents a general binary
relationship that describes an activity between relationship that describes an activity between
two classes. two classes.
An association is usually represented as a data field An association is usually represented as a data field
in the class.in the class.
Student FacultyCourse*5..60Take Teach
0..3 1Teacher
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
66
Representing Association in ClassesAn association is usually represented as a data field in the class. An association is usually represented as a data field in the class.
public class Student {
private Course[]
courseList;
/** Data fields */
/** Constructors */
/** Methods */
}
public class Course {
/** Data fields */
/** Constructors */
/** Methods */
}
public class Faculty {
private Course[]
courseList;
/** Data fields */
/** Constructors */
/** Methods */
}
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
67
Aggregation
AggregationAggregation is a special form of association, is a special form of association,
which represents an ownership relationship which represents an ownership relationship
between two classes. Aggregation models the between two classes. Aggregation models the
relationship like has-a, part-of, owns, and relationship like has-a, part-of, owns, and
employed-by.employed-by.
Magazine ConsultantPublisher1*
Owned by Employed by**
Expert
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
68
Aggregation An object that represents the whole is An object that represents the whole is
associated with a set of objects that associated with a set of objects that represent its componentsrepresent its components
Aggregation is both transitive and Aggregation is both transitive and antisymmetricantisymmetric
The components must be from the same The components must be from the same semantic domain (“composed of” not semantic domain (“composed of” not “made of”)“made of”)
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
69
Composition An Object maybe owned by several other An Object maybe owned by several other
aggregating objectsaggregating objects• If an object is exclusively owed by an aggregating If an object is exclusively owed by an aggregating
object the relationship is called object the relationship is called CompositionComposition• Example:Example:• ““A StudentA Student has a has a Name”Name” is Composition is Composition
relationshiprelationship• ““A A StudentStudent has an has an Address”Address” is an Aggregation is an Aggregation
relationshiprelationship
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
70
Composition vs. Aggregation
Name Address Person 1
*
Composition Aggregation *
*
Composition Composition is a “strong” associationis a “strong” associationAggregation Aggregation is a “weak” associationis a “weak” association
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
71
Behavior Behavioral relationship mechanisms provide a Behavioral relationship mechanisms provide a
way to organize objects and classes in either way to organize objects and classes in either peer-peer-to-peerto-peer (association) or (association) or hierarchicalhierarchical (gen/spec (gen/spec and aggregation) structuresand aggregation) structures
Behavioral analysisBehavioral analysis is the process of looking at is the process of looking at how each object (class) provides its serviceshow each object (class) provides its services
In In staticstatic behavior the operations in the method behavior the operations in the method will not be affected by external or internal events will not be affected by external or internal events
With With dynamicdynamic behaviors, the current state of an behaviors, the current state of an object determines its behaviorobject determines its behavior
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
72
Rules Relationships are mechanisms for specifying Relationships are mechanisms for specifying data semanticsdata semantics Static and dynamic behaviors capture a system’s Static and dynamic behaviors capture a system’s procedural procedural
semanticssemantics RulesRules are used to capture a systems are used to capture a systems declarative semanticsdeclarative semantics Declarative semantics address the issues of global control Declarative semantics address the issues of global control
description and business rulesdescription and business rules Control rulesControl rules Business rulesBusiness rules Exception handling rulesException handling rules Contention rulesContention rules TriggersTriggers
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
73
Building a Specification Model
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
74
Building a Specification Model
The OO way of modeling reality does not try to The OO way of modeling reality does not try to organize all of realityorganize all of reality
We usually try to model only the relevant features We usually try to model only the relevant features of a specific application domain of a specific application domain
One way of bounding the domain is to use One way of bounding the domain is to use Use Use CasesCases
Uses cases Uses cases capture the functional requirements and capture the functional requirements and business-value propositions of a proposed system business-value propositions of a proposed system along with the high-level processes needed to along with the high-level processes needed to achieve those propositionsachieve those propositions
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
75
Building a Specification Model
A use case:A use case: Specifies a sequence of actions, including Specifies a sequence of actions, including
variants, that a system performs and that yields an variants, that a system performs and that yields an observable result of value to an actorobservable result of value to an actor
Is a description of all the possible sequences of Is a description of all the possible sequences of interactions among the system and one or more interactions among the system and one or more actors in response to some initial stimulus by one actors in response to some initial stimulus by one of the actorsof the actors
Is a collection of possible sequences of Is a collection of possible sequences of interactions between the system under discussion interactions between the system under discussion and its external actors, related to a particular goaland its external actors, related to a particular goal
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
76
Use Cases Uses cases are concerned with the actors and the Uses cases are concerned with the actors and the
sequences of interactions between themsequences of interactions between them Some important concepts include:Some important concepts include:
The The goalgoal - the business value to the user - the business value to the user The The systemsystem - the application - the application An An actoractor – external entity that interacts with the system – external entity that interacts with the system Use caseUse case – describes an interaction that achieves a goal – describes an interaction that achieves a goal
for an actorfor an actor Use-case bundleUse-case bundle – a collection of highly correlated use – a collection of highly correlated use
casescases
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
77
Use Cases The The GoalGoal
Use cases attempt to capture the value Use cases attempt to capture the value propositions from an external viewpropositions from an external view
The goal is to capture the business The goal is to capture the business value of the system from the user’s value of the system from the user’s perspectiveperspective
The The SystemSystemUsually viewed as a “black-box”Usually viewed as a “black-box”
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
78
Use Cases The ActorsThe Actors
Uses cases divide the world into two parts: the Uses cases divide the world into two parts: the system and the users (external entities that use it)system and the users (external entities that use it)
Actors are a way of categorizing system users Actors are a way of categorizing system users who share a set of common interactions to who share a set of common interactions to achieve a goalachieve a goal
An actor represents an external entity that can An actor represents an external entity that can initiate actions or receive requests from the initiate actions or receive requests from the systemsystem
A specific user is an instance of an actorA specific user is an instance of an actor The set of requests/responses from/to the actors The set of requests/responses from/to the actors
represents the system boundaries represents the system boundaries
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
79
Use Cases Use Case and ScenarioUse Case and Scenario
A use case describes a system in terms of A use case describes a system in terms of sequences of interactions between various actors sequences of interactions between various actors and the systemand the system
A A scenarioscenario is a short narrative that outlines a is a short narrative that outlines a sequence of requests and responses between a sequence of requests and responses between a user and the system -“what happens next”user and the system -“what happens next”
A scenario describes how a user will use the A scenario describes how a user will use the system to achieve a goalsystem to achieve a goal
A use case is the generalized form of a family of A use case is the generalized form of a family of scenariosscenarios
A scenario is a specific instance of a use caseA scenario is a specific instance of a use case
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
80
Use Cases The Use Case describesThe Use Case describes
The The pre-conditionspre-conditions that must exist for it to that must exist for it to be validbe valid
The The post-conditionspost-conditions that define the state of that define the state of the system after the use case is concludedthe system after the use case is concluded
Detailed Detailed business logicbusiness logic that is performed that is performed (technology independent)(technology independent)
Business Business exceptionsexceptions that can occur that can occur Business Business constraintsconstraints that apply to the that apply to the
system when reacting to a specific user system when reacting to a specific user requestrequest
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
81
Use Cases To effectively capture the functional aspects To effectively capture the functional aspects
of a system the description of the system must of a system the description of the system must be kept at a consistent level of abstractionbe kept at a consistent level of abstraction
To successfully develop use cases we must To successfully develop use cases we must know the dimension of the functional know the dimension of the functional description we are trying to capturedescription we are trying to capture
These dimensions include:These dimensions include: High-level and low-levelHigh-level and low-level Primary and secondaryPrimary and secondary Essential and concreteEssential and concrete
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
82
Use Cases
High-level functional descriptionsHigh-level functional descriptions Provide general and brief descriptions of Provide general and brief descriptions of
the essence of the business values provided the essence of the business values provided by the systemby the system
Low-level functional descriptionsLow-level functional descriptions Provide details showing the exact order of Provide details showing the exact order of
activities, tasks, or alternativesactivities, tasks, or alternatives
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
83
Use Cases Primary functionsPrimary functions
Describe the essential functionality provided to Describe the essential functionality provided to the userthe user
Secondary functionsSecondary functions Deal with rare and exceptional casesDeal with rare and exceptional cases
Essential functionsEssential functions Describe business solutions that are independent Describe business solutions that are independent
of implementation (hardware and software black-of implementation (hardware and software black-box)box)
Concrete functionsConcrete functions Describe use cases that are design dependent Describe use cases that are design dependent
(clear-box)(clear-box)
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
84
Drop Course
Register
Add Course
Delete Course
Cancel Course
Course Registration System
Student
Admin Prof
High-level, primary, essential use case diagram
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
85
Finding Objects and Identifying Responsibilities
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
86
Finding Objects and Identifying Responsibilities
When we analyze systems, we create When we analyze systems, we create models of the application domain of models of the application domain of interestinterest
Although much simpler than reality, if Although much simpler than reality, if the model is rich enough it can help us the model is rich enough it can help us understand the business reality and understand the business reality and manage complexitymanage complexity
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
87
Finding Objects and Identifying Responsibilities
With OO analysis we model reality With OO analysis we model reality with objects as building blockswith objects as building blocks
We describe our world using object We describe our world using object categories (classes) or object types categories (classes) or object types (interfaces)(interfaces)
We assign service prototypes to We assign service prototypes to interfaces interfaces
We assign attributes and services to We assign attributes and services to categoriescategories
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
88
Finding Objects and Identifying Responsibilities
We define relationships between We define relationships between classes (gen-spec, agg-comp, links)classes (gen-spec, agg-comp, links)
Interfaces can be organized using Interfaces can be organized using generalization/specializationgeneralization/specialization
The description of service methods is The description of service methods is captured by pseudocode or UMLcaptured by pseudocode or UML
The behavior of the system is modeled The behavior of the system is modeled as a sequence of messages sent as a sequence of messages sent between objects that are instances of between objects that are instances of the categories or typesthe categories or types
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
89
Finding Objects and Identifying Responsibilities
The final OO model should:The final OO model should:Organize the data into objects and Organize the data into objects and
classes and give the data a structure classes and give the data a structure via relationships (gen/spec, via relationships (gen/spec, agg/comp, links)agg/comp, links)
Organize the services into conceptual Organize the services into conceptual groups via classes or interfaces groups via classes or interfaces
Specify local functional behaviorsSpecify local functional behaviorsCapture control or global behaviorCapture control or global behaviorCapture constraintsCapture constraints
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
90
Finding Objects and Identifying Responsibilities
Two views on how objects come into being: Two views on how objects come into being: empiricistempiricist and and phenomenalistphenomenalist
EmpiricistEmpiricist Objects exist already and are waiting to be perceivedObjects exist already and are waiting to be perceived Developers are blind to existing objects due to their Developers are blind to existing objects due to their
reliance on functional decomposition reliance on functional decomposition PhenomenalistPhenomenalist
Objects come from the world and our consciousness via a Objects come from the world and our consciousness via a dialectical processdialectical process
Real-world objects are a reflection of social relations and Real-world objects are a reflection of social relations and the human thinking processthe human thinking process
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
91
Finding Objects and Identifying Responsibilities
Objects can be identified as use cases Objects can be identified as use cases are writtenare written
Steps to finding objects:Steps to finding objects:Obtain a narrative or informal Obtain a narrative or informal
description of the problemdescription of the problemUse the nouns, pronouns, and noun Use the nouns, pronouns, and noun
phrases to identify objects, categories phrases to identify objects, categories and typesand types
Use verbs and predicate phrases to Use verbs and predicate phrases to identify servicesidentify services
CIS225 - Advanced Java Richard C. Lee and William M. Tepfenhart
92
Summary The Object-Oriented ParadigmThe Object-Oriented Paradigm Managing Complexity with Managing Complexity with
AbstractionAbstraction Specification ModelsSpecification Models Objects and ResponsibilitiesObjects and Responsibilities Static and Dynamic BehaviorStatic and Dynamic Behavior The Unified Modeling LanguageThe Unified Modeling Language Design PatternsDesign Patterns