lecture01

115
Object-Oriented Object-Oriented Programming (OOP) Programming (OOP) Lecture No. 1 Lecture No. 1

Upload: javaria-chiragh

Post on 25-May-2015

516 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Lecture01

Object-Oriented Object-Oriented Programming (OOP)Programming (OOP)

Lecture No. 1Lecture No. 1

Page 2: Lecture01

Course ObjectiveCourse Objective

►Objective of this course is to make Objective of this course is to make students familiar with the concepts of students familiar with the concepts of object-oriented programmingobject-oriented programming

►Concepts will be reinforced by their Concepts will be reinforced by their implementation in C++implementation in C++

Page 3: Lecture01

Course ContentsCourse Contents

►Object-OrientationObject-Orientation►Objects and ClassesObjects and Classes►OverloadingOverloading► InheritanceInheritance►PolymorphismPolymorphism►Generic ProgrammingGeneric Programming►Exception HandlingException Handling► Introduction to Design PatternsIntroduction to Design Patterns

Page 4: Lecture01

BooksBooks

►C++ How to ProgramC++ How to ProgramBy Deitel & DeitelBy Deitel & Deitel

►The C++ Programming LanguageThe C++ Programming LanguageBy Bjarne StroustrupBy Bjarne Stroustrup

►Object-Oriented Software EngineeringObject-Oriented Software EngineeringBy Jacobson, Christerson, Jonsson, OvergaardBy Jacobson, Christerson, Jonsson, Overgaard

Page 5: Lecture01

Object-Orientation (OO)Object-Orientation (OO)

Page 6: Lecture01

What is Object-Orientation?What is Object-Orientation?

►A technique for system modelingA technique for system modeling

►OO model consists of several OO model consists of several interacting objectsinteracting objects

Page 7: Lecture01

What is a Model?What is a Model?

►A model is an abstraction of somethingA model is an abstraction of something

►Purpose is to understand the product Purpose is to understand the product before developing itbefore developing it

Page 8: Lecture01

Examples – ModelExamples – Model

►Highway mapsHighway maps

►Architectural modelsArchitectural models

►Mechanical modelsMechanical models

Page 9: Lecture01

Example – OO ModelExample – OO Model

Page 10: Lecture01

……Example – OO ModelExample – OO Model

►ObjectsObjects AliAli HouseHouse CarCar TreeTree

► InteractionsInteractions Ali lives in the houseAli lives in the house Ali drives the carAli drives the car

Ali

Car

House

Tree

lives-in

drives

Page 11: Lecture01

Object-Orientation - Object-Orientation - Advantages Advantages

►People think in terms of objectsPeople think in terms of objects

►OO models map to realityOO models map to reality

►Therefore, OO models areTherefore, OO models are easy to developeasy to develop easy to understandeasy to understand

Page 12: Lecture01

What is an Object?What is an Object?

An object isAn object is

►Something tangible (Ali, Car)Something tangible (Ali, Car)

►Something that can be apprehended Something that can be apprehended intellectually (Time, Date)intellectually (Time, Date)

Page 13: Lecture01

… … What is an Object?What is an Object?

An object hasAn object has

►State (attributes)State (attributes)►Well-defined behaviour (operations)Well-defined behaviour (operations)►Unique identityUnique identity

Page 14: Lecture01

Example – Ali is a Tangible Example – Ali is a Tangible ObjectObject

►State (attributes)State (attributes) NameName AgeAge

►behaviour (operations)behaviour (operations) WalksWalks EatsEats

► IdentityIdentity His nameHis name

Page 15: Lecture01

Example – Car is a Tangible Example – Car is a Tangible ObjectObject

►State (attributes)State (attributes)- Color- Color

- Model- Model

►behaviour (operations)behaviour (operations)- Accelerate- Accelerate - Start Car- Start Car

- Change Gear- Change Gear

► IdentityIdentity- Its registration number- Its registration number

Page 16: Lecture01

Example – Time is an Object Example – Time is an Object Apprehended IntellectuallyApprehended Intellectually

►State (attributes)State (attributes)- Hours- Hours - Seconds- Seconds

- Minutes- Minutes

►behaviour (operations)behaviour (operations)- Set Hours- Set Hours - Set Seconds- Set Seconds

- Set Minutes- Set Minutes► IdentityIdentity

- Would have a unique ID in the model- Would have a unique ID in the model

Page 17: Lecture01

Example – Date is an Object Example – Date is an Object Apprehended IntellectuallyApprehended Intellectually

►State (attributes)State (attributes)- YearYear - Day- Day- MonthMonth

►behaviour (operations)behaviour (operations)- Set Year- Set Year - Set Day- Set Day

- Set Month- Set Month

► IdentityIdentity- Would have a unique ID in the model- Would have a unique ID in the model

Page 18: Lecture01

Object-Oriented Programming (OOP)

Lecture No. 2

Page 19: Lecture01

Information Hiding

►Information is stored within the object

►It is hidden from the outside world

►It can only be manipulated by the object itself

Page 20: Lecture01

Example – Information Hiding

►Ali’s name is stored within his brain

►We can’t access his name directly

►Rather we can ask him to tell his name

Page 21: Lecture01

Example – Information Hiding

►A phone stores several phone numbers

►We can’t read the numbers directly from the SIM card

►Rather phone-set reads this information for us

Page 22: Lecture01

Information HidingAdvantages

►Simplifies the model by hiding implementation details

►It is a barrier against change propagation

Page 23: Lecture01

Encapsulation

►Data and behaviour are tightly coupled inside an object

►Both the information structure and implementation details of its operations are hidden from the outer world

Page 24: Lecture01

Example – Encapsulation

►Ali stores his personal information and knows how to translate it to the desired language

►We don’t know How the data is stored How Ali translates this information

Page 25: Lecture01

Example – Encapsulation

►A Phone stores phone numbers in digital format and knows how to convert it into human-readable characters

►We don’t know How the data is stored How it is converted to human-readable

characters

Page 26: Lecture01

Encapsulation – Advantages

►Simplicity and clarity

►Low complexity

►Better understanding

Page 27: Lecture01

Object has an Interface

►An object encapsulates data and behaviour

►So how objects interact with each other?►Each object provides an interface

(operations)►Other objects communicate through this

interface

Page 28: Lecture01

Example – Interface of a Car

►Steer Wheels►Accelerate►Change Gear►Apply Brakes►Turn Lights On/Off

Page 29: Lecture01

Example – Interface of a Phone

►Input Number►Place Call►Disconnect Call►Add number to address book►Remove number►Update number

Page 30: Lecture01

Implementation

►Provides services offered by the object interface

►This includes Data structures to hold object state Functionality that provides required

services

Page 31: Lecture01

Example – Implementation of Gear Box

►Data Structure Mechanical structure of gear box

►Functionality Mechanism to change gear

Page 32: Lecture01

Example – Implementation of Address Book in a Phone

►Data Structure SIM card

►Functionality Read/write circuitry

Page 33: Lecture01

Separation of Interface & Implementation

►Means change in implementation does not effect object interface

►This is achieved via principles of information hiding and encapsulation

Page 34: Lecture01

Example – Separation of Interface & Implementation

►A driver can drive a car independent of engine type (petrol, diesel)

►Because interface does not change with the implementation

Page 35: Lecture01

Example – Separation of Interface & Implementation

►A driver can apply brakes independent of brakes type (simple, disk)

►Again, reason is the same interface

Page 36: Lecture01

Advantages of Separation

►Users need not to worry about a change until the interface is same

►Low Complexity

►Direct access to information structure of an object can produce errors

Page 37: Lecture01

Messages

►Objects communicate through messages

►They send messages (stimuli) by invoking appropriate operations on the target object

►The number and kind of messages that can be sent to an object depends upon its interface

Page 38: Lecture01

Examples – Messages

►A Person sends message (stimulus) “stop” to a Car by applying brakes

►A Person sends message “place call” to a Phone by pressing appropriate button

Page 39: Lecture01

Object-Oriented Programming (OOP)

Lecture No. 3

Page 40: Lecture01

Abstraction

►Abstraction is a way to cope with complexity.

►Principle of abstraction:

“Capture only those details about an object that are relevant to current perspective”

Page 41: Lecture01

Example – Abstraction

►Attributes- Name - Employee

ID- Student Roll No - Designation- Year of Study - Salary- CGPA - Age

Ali is a PhD student and teaches BS students

Page 42: Lecture01

Example – Abstraction

Ali is a PhD student and teaches BS students

►behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - Walk

Page 43: Lecture01

Example – Abstraction

►Attributes- Name - Employee

ID- Student Roll No - Designation- Year of Study - Salary- CGPA - Age

Student’s Perspective

Page 44: Lecture01

Example – Abstraction

Student’s Perspective

►behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - Walk

Page 45: Lecture01

Example – Abstraction

►Attributes- Name - Employee

ID- Student Roll No - Designation- Year of Study - Salary- CGPA - Age

Teacher’s Perspective

Page 46: Lecture01

Example – Abstraction

Teacher’s Perspective

►behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - Walk

Page 47: Lecture01

Example – Abstraction

►Ordinary PerspectiveA pet animal with Four Legs A Tail Two Ears Sharp Teeth

►Surgeon’s PerspectiveA being with A Skeleton Heart Kidney Stomach

A cat can be viewed with different perspectives

Page 48: Lecture01

Example – Abstraction

Driver’s View

Engineer’s View

Page 49: Lecture01

Abstraction – Advantages

►Simplifies the model by hiding irrelevant details

►Abstraction provides the freedom to defer implementation decisions by avoiding commitment to details

Page 50: Lecture01

Classes

►In an OO model, some of the objects exhibit identical characteristics (information structure and behaviour)

►We say that they belong to the same class

Page 51: Lecture01

Example – Class

►Ali studies mathematics►Anam studies physics►Sohail studies chemistry

►Each one is a Student►We say these objects are instances of

the Student class

Page 52: Lecture01

Example – Class

►Ahsan teaches mathematics►Aamir teaches computer science►Atif teaches physics

►Each one is a teacher►We say these objects are instances of

the Teacher class

Page 53: Lecture01

Graphical Representation of Classes

(Class Name)

(attributes)

(operations)

(Class Name)

Normal Form

Suppressed Form

Page 54: Lecture01

Example – Graphical Representation of Classes

Circlecenterradius

drawcomputeArea

Normal Form

Suppressed Form

Circle

Page 55: Lecture01

Example – Graphical Representation of Classes

Personnameagegendereatwalk

Normal Form

Suppressed Form

Person

Page 56: Lecture01

Inheritance

►A child inherits characteristics of its parents

►Besides inherited characteristics, a child may have its own unique characteristics

Page 57: Lecture01

Inheritance in Classes

►If a class B inherits from class A then it contains all the characteristics (information structure and behaviour) of class A

►The parent class is called base class and the child class is called derived class

►Besides inherited characteristics, derived class may have its own unique characteristics

Page 58: Lecture01

Example – Inheritance

Person

TeacherDoctorStudent

Page 59: Lecture01

Example – Inheritance

Shape

CircleTriangleLine

Page 60: Lecture01

Inheritance – “IS A” or“IS A KIND OF” Relationship

►Each derived class is a special kind of its base class

Page 61: Lecture01

Example – “IS A” Relationship

Personnameagegendereatwalk

TeacherdesignationsalaryteachtakeExam

StudentprogramstudyYearstudyheldExam

DoctordesignationsalarycheckUpprescribe

Page 62: Lecture01

Example – “IS A” Relationship

ShapecolorcoorddrawrotatesetColor

CircleradiusdrawcomputeArea

Linelengthdraw

Triangleangle

drawcomputeArea

Page 63: Lecture01

Inheritance – Advantages

►Reuse

►Less redundancy

►Increased maintainability

Page 64: Lecture01

Reuse with Inheritance

►Main purpose of inheritance is reuse►We can easily add new classes by

inheriting from existing classes Select an existing class closer to the

desired functionality Create a new class and inherit it from the

selected class Add to and/or modify the inherited

functionality

Page 65: Lecture01

Example ReuseShape

colorcoorddrawrotatesetColor

CircleradiusdrawcomputeArea

Linelengthdraw

Triangleangle

drawcomputeArea

Page 66: Lecture01

Example ReusePerson

nameagegendereatwalk

TeacherdesignationsalaryteachtakeExam

StudentprogramstudyYearstudyheldExam

DoctordesignationsalarycheckUpprescribe

Page 67: Lecture01

Example ReusePerson

nameagegendereatwalk

TeacherdesignationsalaryteachtakeExam

StudentprogramstudyYearstudyheldExam

DoctordesignationsalarycheckUpprescribe

Page 68: Lecture01

Object-Oriented Programming (OOP)

Lecture No. 4

Page 69: Lecture01

Recap – Inheritance

►Derived class inherits all the characteristics of the base class

►Besides inherited characteristics, derived class may have its own unique characteristics

►Major benefit of inheritance is reuse

Page 70: Lecture01

Concepts Related with Inheritance

►Generalization

►Subtyping (extension)

►Specialization (restriction)

Page 71: Lecture01

Generalization

►In OO models, some classes may have common characteristics

►We extract these features into a new class and inherit original classes from this new class

►This concept is known as Generalization

Page 72: Lecture01

Example – Generalization

CirclecolorverticesradiusmovesetColorcomputeArea

LinecolorverticeslengthmovesetColorgetLength

Trianglecolorverticesangle

movesetColorcomputeArea

Page 73: Lecture01

Example – Generalization

ShapecolorverticesmovesetColor

CircleradiuscomputeArea

LinelengthgetLength

Triangleangle

computeArea

Page 74: Lecture01

Example – Generalization

TeachernameagegenderdesignationsalaryteachtakeExameatwalk

StudentnameagegenderprogramstudyYearstudyheldExameatwalk

DoctornameagegenderdesignationsalarycheckUpprescribeeatwalk

Page 75: Lecture01

Example – GeneralizationPerson

nameagegendereatwalk

TeacherdesignationsalaryteachtakeExam

StudentprogramstudyYearstudyheldExam

DoctordesignationsalarycheckUpprescribe

Page 76: Lecture01

Sub-typing & Specialization

►We want to add a new class to an existing model

►Find an existing class that already implements some of the desired state and behaviour

►Inherit the new class from this class and add unique behaviour to the new class

Page 77: Lecture01

Sub-typing (Extension)

►Sub-typing means that derived class is behaviourally compatible with the base class

►Behaviourally compatible means that base class can be replaced by the derived class

Page 78: Lecture01

Example –Sub-typing (Extension)

Personnameagegendereatswalks

StudentprogramstudyYear

studytakeExam

Page 79: Lecture01

Example – Sub-typing (Extension)

ShapecolorverticessetColormove

CircleradiuscomputeCFcomputeArea

Page 80: Lecture01

Specialization (Restriction)

►Specialization means that derived class is behaviourally incompatible with the base class

►Behaviourally incompatible means that base class can’t always be replaced by the derived class

Page 81: Lecture01

Example – Specialization (Restriction)

Personage : [0..100]…

Adultage : [18..100]…

setAge( a )…

setAge( a )…

age = a

If age < 18 then errorelse age = a

Page 82: Lecture01

Example – Specialization (Restriction)

IntegerSet…

NaturalSet…

add( elem )…

add( elem )…

add element to the set

If elem < 1 then errorelse

add element to the set

Page 83: Lecture01

Overriding

►A class may need to override the default behaviour provided by its base class

►Reasons for overriding Provide behaviour specific to a derived class Extend the default behaviour Restrict the default behaviour Improve performance

Page 84: Lecture01

Example – Specific BehaviourShape

colorverticesdrawmovesetColor

CircleradiusdrawcomputeArea

Linelengthdraw

Triangleangle

drawcomputeArea

Page 85: Lecture01

Example – Extension

Windowwidthheightopenclosedraw

DialogBoxcontrolsenabledraw

1- Invoke Window’s draw2- draw the dialog box

Page 86: Lecture01

Example – Restriction

IntegerSet…

NaturalSet…

add( elem )…

add( elem )…

Add element to the set

If elem < 1 then give errorelse

Add element to the set

Page 87: Lecture01

Example – Improve Performance

► Class Circle overrides rotate operation of class Shape with a Null operation.

ShapecolorcoorddrawrotatesetColor

Circleradiusdrawrotate

Page 88: Lecture01

Abstract Classes

►An abstract class implements an abstract concept

►Main purpose is to be inherited by other classes

►Can’t be instantiated►Promotes reuse

Page 89: Lecture01

Example – Abstract Classes

TeacherDoctorStudent

►Here, Person is an abstract class

Personnameagegendereatwalk

Page 90: Lecture01

Example – Abstract Classes

BusTruckCar

►Here, Vehicle is an abstract class

VehiclecolormodelaccelerateapplyBrakes

Page 91: Lecture01

Concrete Classes

►A concrete class implements a concrete concept

►Main purpose is to be instantiated

►Provides implementation details specific to the domain context

Page 92: Lecture01

Example – Concrete Classes

►Here, Student, Teacher and Doctor are concrete classes

TeacherDoctorStudent

programstudyYearstudyheldExam

Person

Page 93: Lecture01

Example – Concrete Classes

• Here, Car, Bus and Truck are concrete classes

BusCar

Vehicle

Truckcapacityloadunload

Page 94: Lecture01

Object oriented programming

(OOP)Lecture No. 7

Page 95: Lecture01

Class

►Class is a tool to realize objects►Class is a tool for defining a new type

Page 96: Lecture01

Example

►Lion is an object►Student is an object►Both has some attributes and some

behaviors

Page 97: Lecture01

Uses

►The problem becomes easy to understand

►Interactions can be easily modeled

Page 98: Lecture01

Type in C++

►Mechanism for user defined types are Structures Classes

►Built-in types are like int, float and double

►User defined type can be Student in student management system Circle in a drawing software

Page 99: Lecture01

Abstraction

►Only include details in the system that are required for making a functional system

►Student Name Address Sibling Father Business

Relevant to our problem

Not relevant to our problem

Page 100: Lecture01

Defining a New User Defined Type

class ClassName

{

DataType MemberVariable;

ReturnType MemberFunction();

};

Syntax

Syntax

Page 101: Lecture01

Example

class Student{int rollNo;char *name;float CGPA;char *address;

…void setName(char *newName);void setRollNo(int newRollNo);

…};

Member variables

Mem

ber F

un

ctions

Page 102: Lecture01

Why Member Function

►They model the behaviors of an object►Objects can make their data invisible►Object remains in consistent state

Page 103: Lecture01

Example

Student aStudent;

aStudent.rollNo = 514;

aStudent.rollNo = -514; //Error

Page 104: Lecture01

Object and Class

►Object is an instantiation of a user defined type or a class

Page 105: Lecture01

Declaring class variables

►Variables of classes (objects) are declared just like variables of structures and built-in data types

TypeName VaraibaleName;int var;Student aStudent;

Page 106: Lecture01

Accessing members

►Members of an object can be accessed using dot operator (.) to access via the variable

name arrow operator (->) to access via a pointer

to an object

►Member variables and member functions are accessed in a similar fashion

Page 107: Lecture01

Example

class Student{int rollNo;void setRollNo(int aNo);

};

Student aStudent;aStudent.rollNo;

Error

Page 108: Lecture01

Access specifiers

Page 109: Lecture01

Access specifiers

►There are three access specifiers ‘public’ is used to tell that member can be

accessed whenever you have access to the object

‘private’ is used to tell that member can only be accessed from a member function

‘protected’ to be discussed when we cover inheritance

Page 110: Lecture01

Example

class Student{private:char * name;int rollNo;

public:void setName(char *);void setRollNo(int);

...};

Cannot be accessed outside class

Can be accessed outside class

Page 111: Lecture01

Example

class Student{...int rollNo;

public:void setRollNo(int aNo);

};int main(){Student aStudent;aStudent.SetRollNo(1);

}

Page 112: Lecture01

Default access specifiers

►When no access specifier is mentioned then by default the member is considered private member

Page 113: Lecture01

Example

class Student

{

char * name;

int RollNo;

};

class Student

{

private:

char * name;

int RollNo;

};

Page 114: Lecture01

Example

class Student

{

char * name;

int RollNo;

void SetName(char *);

};

Student aStudent;

aStudent.SetName(Ali);

Error

Page 115: Lecture01

Example

class Student{char * name;int RollNo;

public:void setName(char *);

};Student aStudent;aStudent.SetName(“Ali”);