Object-Oriented Programming (OOP) Lecture No. 1
Object-Oriented Programming (OOP) Lecture No. 1
Object-Oriented Programming (OOP) Lecture No. 1
(OOP)
Lecture No. 1
Course Objective
► Concepts
will be reinforced by their
implementation in Java
Course Contents
► Object-Orientation
► Objects and Classes
► Overloading
► Inheritance
► Polymorphism
► Java General Programming
► Introduction to Design Patterns
Books
Grading Policy
► Assignments 15 %
► Quizzes 15 %
► Mid-Term 30 %
► Final 40 %
Object-Orientation (OO)
What is Object-Orientation?
► Highway maps
► Architectural models
► Mechanical models
Example – OO Model
…Example – OO Model
► Objects lives-in
Ali House
Ali
drives
House
Car
Car Tree
Tree
► Interactions
Ali lives in the house
Ali drives the car
Object-Orientation - Advantages
► People think in terms of objects
► State (attributes)
► Well-defined behaviour (operations)
► Unique identity
Example – Ali is a Tangible Object
► State (attributes)
Name
Age
► behaviour (operations)
Walks
Eats
► Identity
His name
Example – Car is a Tangible Object
► State (attributes)
- Color
- Model
► behaviour (operations)
- Accelerate - Start Car
- Change Gear
► Identity
- Its registration number
Example – Time is an Object
Apprehended Intellectually
► State (attributes)
- Hours - Seconds
- Minutes
► behaviour (operations)
- Set Hours - Set Seconds
- Set Minutes
► Identity
- Would have a unique ID in the model
Example – Date is an Object
Apprehended Intellectually
► State (attributes)
- Year - Day
- Month
► behaviour (operations)
- Set Year - Set Day
- Set Month
► Identity
- Would have a unique ID in the model
Information Hiding
► Simplifies
the model by hiding
implementation details
► We don’t know
How the data is stored
How Ali translates this information
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
Encapsulation – Advantages
► Low complexity
► Better understanding
Object has an Interface
► This includes
Data structures to hold object state
Functionality that provides required services
Example – Implementation of Gear
Box
► Data Structure
Mechanical structure of gear box
► Functionality
Mechanism to change gear
Example – Implementation of
Address Book in a Phone
► Data Structure
SIM card
► Functionality
Read/write circuitry
Separation of Interface &
Implementation
► Low Complexity
► Principle of abstraction:
► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
Example – Abstraction
Ali is a PhD student and teaches BS
students
► behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
Example – Abstraction
Student’s Perspective
► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
Example – Abstraction
Student’s Perspective
► behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
Example – Abstraction
Teacher’s Perspective
► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
Example – Abstraction
Teacher’s Perspective
► behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
Example – Abstraction
A cat can be viewed with different
perspectives
Engineer’s View
Driver’s View
Abstraction – Advantages
► Abstraction
provides the freedom to defer
implementation decisions by avoiding
commitment to details
Classes
(Class Name)
(Class Name)
(attributes)
Suppressed
(operations)
Form
Normal Form
Example – Graphical Representation
of Classes
Circle
center Circle
radius
draw Suppressed
computeArea Form
Normal Form
Example – Graphical Representation
of Classes
Person
name Person
age
gender Suppressed
eat Form
walk
Normal Form
Inheritance
► Besides
inherited characteristics, a child
may have its own unique characteristics
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
Example – Inheritance
Person
Student Doctor
Teacher
Example – Inheritance
Shape
Line Triangle
Circle
Inheritance – “IS A” or
“IS A KIND OF” Relationship
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
Inheritance – Advantages
► Reuse
► Less redundancy
► Increased maintainability
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
Example Reuse
Shape
color
coord
draw
rotate
setColor
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
Example Reuse
Person
name
age
gender
eat
walk
► Generalization
► Subtyping (extension)
► Specialization (restriction)
Generalization
► In
OO models, some classes may have
common characteristics
Circle Triangle
radius Line angle
computeArea length computeArea
getLength
Example – Generalization
Student
name
age Teacher
gender name
Doctor
program age
name
studyYear gender
age
study designation
gender
heldExam salary
designation
eat teach
salary
walk takeExam
eat checkUp
walk prescribe
eat
walk
Example – Generalization
Person
name
age
gender
eat
walk
► Inherit
the new class from this class and add
unique behaviour to the new class
Sub-typing (Extension)
► Sub-typingmeans that derived class is
behaviourally compatible with the base class
Sub-typing
(Extension) Student
program
studyYear
study
takeExam
Shape
color
vertices
setColor
Example – move
Sub-typing
(Extension)
Circle
radius
computeCF
computeArea
Specialization (Restriction)
► Specialization
means that derived class is
behaviourally incompatible with the base
class
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
Example – Extension
Window
width
height
open
close
draw
DialogBox
1- Invoke Window’s
controls
draw
enable 2- draw the dialog
draw box
Example – Restriction
IntegerSet
…
add( elem ) Add element to
… the set
Circle
radius
draw
rotate
Abstract Classes
Student Doctor
Teacher
► Here, Person is an abstract class
Example – Abstract Classes
Vehicle
color
model
accelerate
applyBrakes
Car Truck
Bus
► Provides
implementation details specific to
the domain context
Example – Concrete Classes
Person
Student Doctor
program Teacher
studyYear
study
heldExam
Vehicle
Car Truck
Bus
capacity
load
unload
Mermaid
Example – Multiple Inheritance
Woman Fish
Mermaid
Example – Multiple Inheritance
Amphibious Vehicle
Example – Multiple Inheritance
Vehicle
► Increased complexity
► Reduced understanding
► Duplicate features
Problem – Duplicate Features
Woman Fish
eat eat
… …
Mermaid
Woman Fish
eat eat
… …
Mermaid
eat Invoke eat
operation of
… desired class
Problem – Duplicate Features
(Diamond Problem)
Vehicle
changeGear
► Object Association
Simple Association
Composition
Aggregation
Simple Association
lives-in
Ali House
1 1
drives
Ali Car
1 *
works-for
Employee Company
* 1
friend
Yasir Ali
1 1
works-for
Employee Company
* 1
drives
Ali Car
1 *
Student 1
Teacher
*
*
Course
Project * *
Language
1
Person
1
Body
Example – Composition of Chair
Back
1
Chair
2 1 4
Arm Seat Leg
Composition is Stronger
Bed
1
1
Cupboard
Example – Aggregation
Garden * Plant
Aggregation is Weaker
► Furniture
can be shifted to another room,
and so can exist independent of a particular
room
Example – Aggregation is Weaker
Circle Triangle
radius Line angle
length
draw draw
computeArea draw computeArea
getLength
Example – Class Compatibility
File
size
…
open
print
…
draw Shape
View
draw
print File
Editor
print
draw Shape
View
draw
draw Shape
View
draw
An Example
Problem Statement
► Develop a graphic editor that can draw
different geometric shapes such as line,
circle and triangle. User can select, move or
rotate a shape. To do so, editor provides
user with a menu listing different
commands. Individual shapes can be
grouped together and can behave as a
single shape.
Identify Classes
Extract nouns in the problem statement
► Shape • Group
► Line • View
► Circle
► Triangle
► Menu
Object Model – Graphic Editor
Shape Group
Line Menu
Circle
View
Triangle
Identify Associations
Extract verbs connecting objects
nn nn nn
Line nn Circle Triangle Group
nn
nn nn
Identify Attributes
Extract properties of the object
From the problem statement
n n n
Line n Circle Triangle Group
length radius angle noOfObjects
n
n
n
Identify Operations
Extract verbs connected with an object
• Line • Circle
– Draw – Draw
– Select – Select
– Move – Move
– Rotate – Rotate
…Identify Operations
Following are selected operations:
• Triangle • Shape
– Draw – Draw
– Select – Select
– Move – Move
– Rotate – Rotate
…Identify Operations
Following are selected operations:
• Group • Menu
– Draw – Open
– Select – Select
– Move – Move
– Rotate – Rotate
…Identify Operations
Extract operations using domain
knowledge
• View
– Add – Select
– Remove – Move
– Group – Rotate
– Show
View
Menu noOfObjects Shape
selected
name color
isOpen vertices
add()
remove()
open() n draw()
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
rotate() n
n n
Line n Triangle Group
n
length angle noOfObjects
Circle
n
draw() radius draw() draw()
n
n draw()
Identify Inheritance
By analyzing requirements
► “Individual
shapes can be grouped together
and can behave as a single shape”
Group inherits from Shape
Refining the Object Model
► Applicationof inheritance demands an
iteration over the whole object model
Share associations
Share attributes
Share operations
n n
Line n Triangle Group
n
length angle noOfObjects
Circle
n
draw() radius draw() draw()
n
n draw()
Class
► Class is a tool to realize objects
► Class is a tool for defining a new type
Example
► Lionis an object
► Student is an object
► Both has some attributes and some
behaviors
Uses
► The problem becomes easy to understand
► Interactions can be easily modeled
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
Abstraction
► Only include details in the system that are
required for making a functional system
► Student
Name
Relevant to our problem
Address
Sibling
Not relevant to our problem
Father Business
Defining a New User Defined Type
class ClassName
{ Syntax
…
DataType MemberVariable;
ReturnType MemberFunction();
…
}; Syntax
Example
class Student
{
int rollNo;
char *name; Member variables
float CGPA;
Member Functions
char *address;
…
void setName(char *newName);
void setRollNo(int newRollNo);
…
};
Why Member Function
► They model the behaviors of an object
► Objects can make their data invisible
► Object remains in consistent state
Example
Student aStudent;
aStudent.rollNo = 514;
TypeName VaraibaleName;
int var;
Student aStudent;
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
Example
class Student{
int rollNo;
void setRollNo(int
aNo);
};
Child
...
Func1
Overriding
class Parent {
public:
void Func1();
void Func1(int);
};
void Print(){
cout <<“Name: ”<< GetName()<<endl
<< “Major:” << major<< endl;
}
...
};
Example
int main(){
Student a(“Ahmad”, “Computer
Science”);
a.Print();
return 0;
}
Output
Output:
Name: Ahmed
Major: Computer Science
Overriding Member Functions of
Base Class
► Deriveclass can override member function
of base class such that the working of
function is based on former
implementation
Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);
void Print(){
Print();//Print of Person
cout<<“Major:” << major <<endl;
}
...
};
Example
int main(){
Student a(“Ahmad”, “Computer
Science”);
a.Print();
return 0;
}
Output
► There will be no output as the compiler
will call the print of the child class from
print of child class recursively
► There is no ending condition
Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);
void Print(){
Person::Print();
cout<<“Major:” << major <<endl;
}
...
};
Example
int main(){
Student a(“Ahmad”, “Computer
Science”);
a.Print();
return 0;
}
Output
Output:
Name: Ahmed
Major: Computer Science
Overriding Member Functions of
Base Class
► Thepointer must be used with care when
working with overridden member
functions
Example
int main(){
Student a(“Ahmad”, “Computer
Scuence”);
Student *sPtr = &a;
sPtr->Print();
Name: Ahmed
Major: Computer Science
Name: Ahmed
Overriding Member Functions of
Base Class
► The member function is called according
to static type
► The static type of pPtr is Person
► The static type of sPtr is Student
Hierarchy of Inheritance
► We represent the classes involved in
inheritance relation in tree like hierarchy
Example
GrandParent
Parent1 Parent2
Child1 Child2
Direct Base Class
►A direct base class is explicitly listed
in a derived class's header with a
colon (:)
class GrandParent{};
class Parent1:
public GrandParent {};
class Child1:public Parent1{};