CS540 Software Design 2Lecture 13
Object-Oriented Object-Oriented ProgrammingProgramming
Objects can be used effectively to Objects can be used effectively to represent real-world entitiesrepresent real-world entities
For instance, an object might For instance, an object might represent a particular employee in a represent a particular employee in a companycompany
Each employee object handles the Each employee object handles the processing and data management processing and data management related to that employeerelated to that employee
CS540 Software Design 3Lecture 13
ObjectsObjects An object has:An object has:
statestate - descriptive characteristics - descriptive characteristics
behaviorsbehaviors - what it can do (or what can be done to - what it can do (or what can be done to it)it)
The state of a bank account includes its account The state of a bank account includes its account number and its current balancenumber and its current balance
The behaviors associated with a bank account include The behaviors associated with a bank account include the ability to make deposits and withdrawalsthe ability to make deposits and withdrawals
Note that the behavior of an object might change its Note that the behavior of an object might change its statestate
CS540 Software Design 4Lecture 13
ClassesClasses An object is defined by a An object is defined by a classclass
A class is the blueprint of an objectA class is the blueprint of an object
Multiple objects can be created from the same Multiple objects can be created from the same classclass
CS540 Software Design 5Lecture 13
Objects and ClassesObjects and Classes
Bank Account
A class(the concept)
John’s Bank AccountBalance: $5,257
An object(the realization)
Bill’s Bank AccountBalance: $1,245,069
Mary’s Bank AccountBalance: $16,833
Multiple objectsfrom the same class
CS540 Software Design 6Lecture 13
AttributesAttributesContain current state of an object.Contain current state of an object.
Attributes can be classified as simple or Attributes can be classified as simple or complex. complex.
Simple attribute can be a primitive type such Simple attribute can be a primitive type such as integer, string, etc., which takes on literal as integer, string, etc., which takes on literal values.values.
Complex attribute can contain collections Complex attribute can contain collections and/or references. and/or references.
Reference attribute represents relationship. Reference attribute represents relationship. complex object:complex object: contains one or more contains one or more
complex attributescomplex attributes
CS540 Software Design 7Lecture 13
Methods and messagesMethods and messages
MethodMethod: : Defines behavior of an object, as a set of encapsulated Defines behavior of an object, as a set of encapsulated functions.functions.
Message: Message: Request from one object to another asking second object to Request from one object to another asking second object to execute one of its methods.execute one of its methods.
(a)
(b)
(a) Object showing attributes and methods(b) Example of a method
CS540 Software Design 8Lecture 13
ClassesClasses
ClassClass: Blueprint for defining a set of similar objects.: Blueprint for defining a set of similar objects.
Objects in a class are called Objects in a class are called instancesinstances..
CS540 Software Design 9Lecture 13
InheritanceInheritance One class can be used to derive another via One class can be used to derive another via
inheritanceinheritance
Classes can be organized into hierarchiesClasses can be organized into hierarchies
Bank Account
Account
Charge Account
Savings Account
Checking Account
CS540 Software Design 10Lecture 13
Inheritance (contd)Inheritance (contd)Inheritance allows one class of objects to be defined as a Inheritance allows one class of objects to be defined as a
special case of a more general class.special case of a more general class.
Special cases are Special cases are subclassessubclasses and more general cases and more general cases are are superclassessuperclasses..
Generalization: process of forming a superclass Specialization: forming a subclass •Subclass inherits all properties of its superclass and can define its own unique properties. •Subclass can redefine inherited methods. •All instances of subclass are instances of superclass. •Principle of substitutability: instance of subclass can be used whenever method/construct expects instance of superclass.•A KIND OF (AKO): Name for relationship between subclass and superclass
CS540 Software Design 11Lecture 13
Types of inheritanceTypes of inheritance
(a)
(b)
(c)
(a) Single(b) Multiple(c) Repeated
(b)
CS540 Software Design 12Lecture 13
Inheritance (contd)Inheritance (contd) Define Define humanBeinghumanBeing to be a to be a classclass
A A humanBeinghumanBeing has has attributesattributes, such as age, , such as age, height, genderheight, gender
Assign values to attributes when describing Assign values to attributes when describing objectobject
Define Parent to be a Define Parent to be a subclasssubclass of HumanBeing of HumanBeing A Parent has all attributes of a HumanBeing, A Parent has all attributes of a HumanBeing,
plus attributes of his/her own (name of oldest plus attributes of his/her own (name of oldest child, number of children)child, number of children)
AA ParentParent inherits all attributes of inherits all attributes of humanBeinghumanBeing The property of inheritance is an essential feature The property of inheritance is an essential feature
of object-oriented languages such as Smalltalk, of object-oriented languages such as Smalltalk, C++, Ada 95, Java (but not C, FORTRAN)C++, Ada 95, Java (but not C, FORTRAN)
CS540 Software Design 13Lecture 13
Inheritance (contd)Inheritance (contd)
UML notationUML notation Inheritance is represented by a large open triangleInheritance is represented by a large open triangle
CS540 Software Design 14Lecture 13
Java implementationJava implementation
CS540 Software Design 15Lecture 13
Overriding and Overriding and OverloadingOverloading
Overriding: Overriding: Process of redefining a property within a Process of redefining a property within a subclass.subclass.
Overloading: Overloading: Allows name of a method to be reused with a Allows name of a method to be reused with a class or across classes.class or across classes.
Overriding Example:Might define method in Staff class to increment salary based on commission
method void giveCommission(float branchProfit) {
salary = salary + 0.02 * branchProfit; }
May wish to perform different calculation for commission in Manager subclass:
method void giveCommission(float branchProfit) {
salary = salary + 0.05 * branchProfit; }
CS540 Software Design 16Lecture 13
Aggregation Aggregation
UML Notation UML Notation
CS540 Software Design 17Lecture 13
AssociationAssociation
UML NotationUML Notation
CS540 Software Design 18Lecture 13
Equivalence of Data and Equivalence of Data and ActionAction
Classical paradigmClassical paradigm record_1.field_2record_1.field_2
Object-oriented paradigmObject-oriented paradigm thisObject.attributeBthisObject.attributeB thisObject.methodC()thisObject.methodC()
CS540 Software Design 19Lecture 13
Example – Chapter 7 Example – Chapter 7 Schach (2002)Schach (2002)
Design of an operating system for a large Design of an operating system for a large mainframe computer. It has been decided that mainframe computer. It has been decided that batch jobs submitted to the computer will be batch jobs submitted to the computer will be classified as high priority, medium priority, or classified as high priority, medium priority, or low priority. There must be three queues for low priority. There must be three queues for incoming batch jobs, one for each job type. incoming batch jobs, one for each job type. When a job is submitted by a user, the job is When a job is submitted by a user, the job is added to the appropriate queue, and when the added to the appropriate queue, and when the operating system decides that a job is ready to be operating system decides that a job is ready to be run, it is removed from its queue and memory is run, it is removed from its queue and memory is allocated to it allocated to it
Design 1 (Next slide)Design 1 (Next slide) Low cohesion—operations on job queues are spread all Low cohesion—operations on job queues are spread all
over productover product
CS540 Software Design 20Lecture 13
Data Encapsulation — Data Encapsulation — Design 1Design 1
CS540 Software Design 21Lecture 13
Data Encapsulation — Data Encapsulation — Design 2Design 2
CS540 Software Design 22Lecture 13
Data EncapsulationData Encapsulation
m_encapsulationm_encapsulation has informational cohesion has informational cohesion m_encapsulation m_encapsulation is an implementation of is an implementation of
data encapsulationdata encapsulation Data structure (Data structure (job_queuejob_queue) together with ) together with
operations performed on that data operations performed on that data structure structure
Advantages Advantages DevelopmentDevelopment MaintenanceMaintenance
CS540 Software Design 23Lecture 13
Data Encapsulation and Data Encapsulation and DevelopmentDevelopment
Data encapsulation is an example of Data encapsulation is an example of abstractionabstraction
Job queue exampleJob queue example Data structureData structure
job_queuejob_queue Three new functionsThree new functions
iinitialize_job_queuenitialize_job_queue add_job_to_queueadd_job_to_queue delete_job_from_queuedelete_job_from_queue
AbstractionAbstraction Conceptualize problem at higher levelConceptualize problem at higher level
job queues and operations on job queuesjob queues and operations on job queues not lower level not lower level
records or arraysrecords or arrays
CS540 Software Design 24Lecture 13
Stepwise RefinementStepwise RefinementStep 1: Design in terms of high level concepts Step 1: Design in terms of high level concepts
It is irrelevant how job queues are implementedIt is irrelevant how job queues are implemented
Step 2: Design low level componentsStep 2: Design low level components
Totally ignore what use will be made of themTotally ignore what use will be made of them In 1st step, assume existence of lower levelIn 1st step, assume existence of lower level
Concern is the behavior of the data structureConcern is the behavior of the data structure job_queuejob_queue
In 2nd step, ignore existence of high levelIn 2nd step, ignore existence of high level Concern is the implementation of that behaviorConcern is the implementation of that behavior
In a larger product, there will be many levels of In a larger product, there will be many levels of abstractionabstraction
CS540 Software Design 25Lecture 13
Data Encapsulation and Data Encapsulation and MaintenanceMaintenance
Identify aspects of product likely to Identify aspects of product likely to changechange
Design product so as to minimize the Design product so as to minimize the effects of changeeffects of change Data structures are unlikely to changeData structures are unlikely to change Implementation may changeImplementation may change
Data encapsulation provides a way to Data encapsulation provides a way to cope with changecope with change
CS540 Software Design 26Lecture 13
Implementation of Implementation of ClassClass JobQueue JobQueue
C++C++
JavaJava
CS540 Software Design 27Lecture 13
Implementation of Implementation of queueHandlerqueueHandler
C++ JavaC++ Java
CS540 Software Design 28Lecture 13
Data Encapsulation and Data Encapsulation and Maintenance (contd)Maintenance (contd)
What happens if queue is now implemented as a What happens if queue is now implemented as a two-way linked list of two-way linked list of JobRecordJobRecord?? Module that uses Module that uses JobRecordJobRecord need not be need not be
changed at all, merely recompiledchanged at all, merely recompiled
C+C+++
JavaJava
CS540 Software Design 29Lecture 13
Abstract Data TypesAbstract Data Types
Problem with both implementationsProblem with both implementations Only one queueOnly one queue
NeedNeed We need: We need:
Data Data typetype + operations performed on + operations performed on instantiations of that data typeinstantiations of that data type
Abstract data typeAbstract data type
CS540 Software Design 30Lecture 13
Abstract Data Type (contd)Abstract Data Type (contd)
(Problems caused by (Problems caused by publicpublic attributes solved later) attributes solved later)
CS540 Software Design 31Lecture 13
Information HidingInformation Hiding Data abstractionData abstraction
Designer thinks at level of an ADTDesigner thinks at level of an ADT Procedural abstractionProcedural abstraction
Define a procedure—extend the language Define a procedure—extend the language Instances of a more general design concept, Instances of a more general design concept,
information hidinginformation hiding Design the modules in way that items likely to Design the modules in way that items likely to
change are hiddenchange are hidden Future change is localizedFuture change is localized Changes cannot affect other modulesChanges cannot affect other modules
CS540 Software Design 32Lecture 13
Information Hiding (contd)Information Hiding (contd)
C++ C++ abstract data abstract data type type implementatiimplementation with on with information information hidinghiding
CS540 Software Design 33Lecture 13
Information Hiding (contd)Information Hiding (contd)
Effect of information hiding via Effect of information hiding via privateprivate attributes attributes
CS540 Software Design 34Lecture 13
Polymorphism and Polymorphism and Dynamic BindingDynamic Binding
Classical paradigmClassical paradigm Must explicitly invoke correct Must explicitly invoke correct
versionversion
CS540 Software Design 35Lecture 13
Polymorphism and Dynamic Polymorphism and Dynamic Binding (contd)Binding (contd)
Object-oriented paradigmObject-oriented paradigm
CS540 Software Design 36Lecture 13
Polymorphism and Dynamic Polymorphism and Dynamic Binding (contd)Binding (contd)
All that is needed is All that is needed is myFile.open()myFile.open() Correct method invoked at run-time Correct method invoked at run-time
(dynamically)(dynamically) Method Method openopen can be applied to objects can be applied to objects
of different classesof different classes PolymorphicPolymorphic
CS540 Software Design 37Lecture 13
Polymorphism and dynamic Polymorphism and dynamic binding (contd)binding (contd)
MethodMethod checkOrder (b : Base)checkOrder (b : Base) can be applied to objects of any subclass ofcan be applied to objects of any subclass of BaseBase
CS540 Software Design 38Lecture 13
Polymorphism and Dynamic Polymorphism and Dynamic Binding (contd)Binding (contd)
Can have a negative impact on Can have a negative impact on maintenancemaintenance Code is hard to understand if there are Code is hard to understand if there are
multiple possibilities for a specific multiple possibilities for a specific methodmethod
Polymorphism and dynamic bindingPolymorphism and dynamic binding Strength and weakness of the object-Strength and weakness of the object-
oriented paradigmoriented paradigm
CS540 Software Design 39Lecture 13
Polymorphism and dynamic Polymorphism and dynamic binding (contd)binding (contd)
Polymorphism: Polymorphism: Means ‘Means ‘many formsmany forms’. ’.
Dynamic Binding:Dynamic Binding: Runtime process of selecting appropriate Runtime process of selecting appropriate method based on an object’s type.method based on an object’s type.
Example: With list consisting of an arbitrary no. of objects from the Staff hierarchy, we can write: list[i]. print
and runtime system will determine which print() method to invoke depending on the object’s (sub)type.
CS540 Software Design 40Lecture 13
Cohesion and Coupling of Cohesion and Coupling of ObjectsObjects
No such thing!No such thing! Object-oriented cohesion and coupling always Object-oriented cohesion and coupling always
reduces to classical cohesionreduces to classical cohesion The only feature unique to the object-oriented The only feature unique to the object-oriented
paradigm is inheritanceparadigm is inheritance Cohesion has nothing to do with inheritanceCohesion has nothing to do with inheritance Two objects with the same functionality have the Two objects with the same functionality have the
same cohesionsame cohesion It does not matter if this functionality is inherited It does not matter if this functionality is inherited
or notor not Similarly, so-called object-oriented coupling Similarly, so-called object-oriented coupling
always reduces to classical coupling always reduces to classical coupling
CS540 Software Design 41Lecture 13
Object-Oriented Metrics Object-Oriented Metrics (contd)(contd)
Two types of so-called object-oriented Two types of so-called object-oriented metricmetric Not related to inheritanceNot related to inheritance
Reduces to a classical metricReduces to a classical metric Inheritance-relatedInheritance-related
May reduce to a classical metricMay reduce to a classical metric No problemNo problem
Classical metrics work just fineClassical metrics work just fine But don’t mislead others by calling them But don’t mislead others by calling them
object-orientedobject-oriented
CS540 Software Design 42Lecture 13
Advantages of ObjectsAdvantages of Objects Same as as advantages of abstract data Same as as advantages of abstract data
typestypes Information hidingInformation hiding Data abstractionData abstraction Procedural abstractionProcedural abstraction
Inheritance provides further data Inheritance provides further data abstractionabstraction Easier and less error-prone product Easier and less error-prone product
developmentdevelopment Easier maintenanceEasier maintenance
Objects are more reusable than modules Objects are more reusable than modules with functional cohesionwith functional cohesion
CS540 Software Design 43Lecture 13
SummarySummary