Вы находитесь на странице: 1из 220

Object-Oriented Programming

(OOP)
Lecture No. 1
Course Objective

► Objective of this course is to make students


familiar with the concepts of object-oriented
programming

► 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?

►A technique for system modeling

► OO model consists of several interacting


objects
What is a Model?

►A model is an abstraction of something

► Purposeis to understand the product before


developing it
Examples – Model

► 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

► OO models map to reality

► Therefore, OO models are


 easy to develop
 easy to understand
What is an Object?
An object is

► Something tangible (Ali, Car)

► Something that can be apprehended


intellectually (Time, Date)
… What is an Object?
An object has

► 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

► Information is stored within the object

► It is hidden from the outside world

► It can only be manipulated by the object


itself
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


Example – Information Hiding

►A phone stores several phone numbers

► Wecan’t read the numbers directly from the


SIM card

► Rather phone-set reads this information for


us
Information Hiding
Advantages

► Simplifies
the model by hiding
implementation details

► It is a barrier against change propagation


Encapsulation

► Data and behaviour are tightly coupled


inside an object

► Boththe information structure and


implementation details of its operations are
hidden from the outer world
Example – Encapsulation

► Alistores 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
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

► Simplicity and clarity

► Low complexity

► Better understanding
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
Example – Interface of a Car
► Steer Wheels
► Accelerate
► Change Gear
► Apply Brakes
► Turn Lights On/Off
Example – Interface of a Phone
► Input Number
► Place Call
► Disconnect Call
► Add number to address book
► Remove number
► Update number
Implementation
► Provides services offered by the object
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

► Means change in implementation does not


effect object interface

► Thisis achieved via principles of information


hiding and encapsulation
Example – Separation of Interface &
Implementation

►A driver can drive a car independent of


engine type (petrol, diesel)

► Becauseinterface does not change with the


implementation
Example – Separation of Interface &
Implementation

►A driver can apply brakes independent of


brakes type (simple, disk)

► Again, reason is the same interface


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

► Low Complexity

► Directaccess to information structure of an


object can produce errors
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
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
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”
Example – Abstraction
Ali is a PhD student and teaches BS
students

► 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

► Ordinary Perspective ► Surgeon’s Perspective


A pet animal with A being with
 Four Legs  A Skeleton
 A Tail  Heart
 Two Ears  Kidney
 Sharp Teeth  Stomach
Example – Abstraction

Engineer’s View

Driver’s View
Abstraction – Advantages

► Simplifies the model by hiding irrelevant


details

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

► Inan OO model, some of the objects exhibit


identical characteristics (information
structure and behaviour)

► We say that they belong to the same class


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
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
Graphical Representation of 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

►A child inherits characteristics of its parents

► 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

► Eachderived class is a special kind of its


base class
Example – “IS A” Relationship
Person
name
age
gender
eat
walk

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
Example – “IS A” Relationship
Shape
color
coord
draw
rotate
setColor

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

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
Example Reuse
Person
name
age
gender
eat
walk

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
Recap – Inheritance
► Derivedclass inherits all the characteristics
of the base class

► Besidesinherited characteristics, derived


class may have its own unique
characteristics

► Major benefit of inheritance is reuse


Concepts Related with
Inheritance

► Generalization

► Subtyping (extension)

► Specialization (restriction)
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


Example – Generalization
Line
color
vertices Circle
length color
move vertices Triangle
setColor radius
color
getLength move
vertices
setColor
angle
computeArea
move
setColor
computeArea
Example – Generalization
Shape
color
vertices
move
setColor

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

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
Sub-typing & Specialization
► Wewant to add a new class to an existing
model

► Findan 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
Sub-typing (Extension)
► Sub-typingmeans that derived class is
behaviourally compatible with the base class

► Behaviourallycompatible means that base


class can be replaced by the derived class
Person
name
age
gender
eats
Example – walks

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

► Behaviourally incompatible means that base


class can’t always be replaced by the
derived class
Example – Specialization
(Restriction)
Person
age : [0..100]

setAge( a ) age = a

Adult If age < 18 then


age : [18..100] error
… else
setAge( a ) age = a

Example – Specialization
(Restriction)
IntegerSet

add( elem ) add element to
… the set

If elem < 1 then


NaturalSet error
… else
add( elem ) add element
… to the set
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
Example – Specific Behaviour
Shape
color
vertices
draw
move
setColor

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

If elem < 1 then


NaturalSet give error
… else
add( elem ) Add element to
… the set
Example – Improve Performance
Shape
color
► Class Circle overrides coord
rotate operation of draw
class Shape with a Null rotate
setColor
operation.

Circle
radius
draw
rotate
Abstract Classes

► An abstract class implements an abstract


concept
► Main purpose is to be inherited by other
classes
► Can’t be instantiated
► Promotes reuse
Example – Abstract Classes
Person
name
age
gender
eat
walk

Student Doctor
Teacher
► Here, Person is an abstract class
Example – Abstract Classes
Vehicle
color
model
accelerate
applyBrakes

Car Truck
Bus

► Here, Vehicle is an abstract class


Concrete Classes
►A concrete class implements a concrete
concept

► Main purpose is to be instantiated

► Provides
implementation details specific to
the domain context
Example – Concrete Classes

Person

Student Doctor
program Teacher
studyYear
study
heldExam

► Here,Student, Teacher and Doctor are


concrete classes
Example – Concrete Classes

Vehicle

Car Truck
Bus
capacity
load
unload

• Here, Car, Bus and Truck are concrete


classes
Multiple Inheritance

► Wemay want to reuse characteristics of


more than one parent class
Example – Multiple Inheritance

Mermaid
Example – Multiple Inheritance

Woman Fish

Mermaid
Example – Multiple Inheritance

Amphibious Vehicle
Example – Multiple Inheritance

Vehicle

Land Vehicle Water Vehicle

Car Amphibious Vehicle Boat


Problems with Multiple
Inheritance

► Increased complexity

► Reduced understanding

► Duplicate features
Problem – Duplicate Features

Woman Fish
eat eat
… …

Mermaid

► Which eat operation Mermaid inherits?


Solution – Override the Common
Feature

Woman Fish
eat eat
… …

Mermaid
eat Invoke eat
operation of
… desired class
Problem – Duplicate Features
(Diamond Problem)
Vehicle
changeGear

Land Vehicle Water Vehicle

Car Amphibious Vehicle Boat

► Which changeGear operation Amphibious


Vehicle inherits?
Solution to Diamond Problem

► Some languages disallow diamond


hierarchy

► Othersprovide mechanism to ignore


characteristics from one side
Association
► Objectsin an object model interact with
each other

► Usuallyan object provides services to


several other objects

► Anobject keeps associations with other


objects to delegate tasks
Kinds of Association
► Class Association
 Inheritance

► Object Association
 Simple Association
 Composition
 Aggregation
Simple Association

► Is the weakest link between objects

► Isa reference by which one object can


interact with some other object

► Is simply called as “association”


Kinds of Simple Association
► w.r.t navigation
 One-way Association
 Two-way Association

► w.r.t number of objects


 Binary Association
 Ternary Association
 N-ary Association
One-way Association

► We can navigate along a single direction


only

► Denoted by an arrow towards the server


object
Example – Association

lives-in
Ali House
1 1

► Ali lives in a House


Example – Association

drives
Ali Car
1 *

► Ali drives his Car


Two-way Association

► We can navigate in both directions

► Denoted by a line between the associated


objects
Example – Two-way Association

works-for
Employee Company
* 1

► Employeeworks for company


► Company employs employees
Example – Two-way Association

friend
Yasir Ali
1 1

► Yasir is a friend of Ali


► Ali is a friend of Yasir
Binary Association

► Associates objects of exactly two classes

► Denoted by a line, or an arrow between the


associated objects
Example – Binary Association

works-for
Employee Company
* 1

► Association“works-for” associates objects of


exactly two classes
Example – Binary Association

drives
Ali Car
1 *

► Association“drives” associates objects of


exactly two classes
Ternary Association

► Associates objects of exactly three classes

► Denoted by a diamond with lines connected


to associated objects
Example – Ternary Association

Student 1
Teacher
*

*
Course

► Objectsof exactly three classes are


associated
Example – Ternary Association

Project * *
Language

1
Person

► Objectsof exactly three classes are


associated
N-ary Association

► An association between 3 or more classes

► Practical examples are very rare


Composition
► An object may be composed of other
smaller objects
► The relationship between the “part” objects
and the “whole” object is known as
Composition
► Composition is represented by a line with a
filled-diamond head towards the composer
object
Example – Composition of Ali
Head
1

Arm Ali Leg


2 2

1
Body
Example – Composition of Chair
Back
1

Chair

2 1 4
Arm Seat Leg
Composition is Stronger

► Composition is a stronger relationship,


because
 Composed object becomes a part of the
composer
 Composed object can’t exist independently
Example – Composition is
Stronger

► Ali is made up of different body parts

► They can’t exist independent of Ali


Example – Composition is
Stronger

► Chair’s body is made up of different parts

► They can’t exist independently


Aggregation
► An object may contain a collection
(aggregate) of other objects
► The relationship between the container and
the contained object is called aggregation
► Aggregation is represented by a line with
unfilled-diamond head towards the
container
Example – Aggregation

Bed
1

Chair Room Table


* 1

1
Cupboard
Example – Aggregation

Garden * Plant
Aggregation is Weaker

► Aggregation is weaker relationship, because


 Aggregate object is not a part of the container
 Aggregate object can exist independently
Example – Aggregation is Weaker

► Furniture is not an intrinsic part of room

► Furniture
can be shifted to another room,
and so can exist independent of a particular
room
Example – Aggregation is Weaker

►A plant is not an intrinsic part of a garden

► Itcan be planted in some other garden, and


so can exist independent of a particular
garden
Class Compatibility
►A class is behaviorally compatible with
another if it supports all the operations of
the other class

► Such a class is called subtype

►A class can be replaced by its subtype


…Class Compatibility
► Derived class is usually a subtype of the
base class

► Itcan handle all the legal messages


(operations) of the base class

► Therefore, base class can always be


replaced by the derived class
Example – Class Compatibility
Shape
color
vertices
move
setColor
draw

Circle Triangle
radius Line angle
length
draw draw
computeArea draw computeArea
getLength
Example – Class Compatibility
File
size

open
print

ASCII File PS File


… PDF File …

print print
… print …

Polymorphism

► Ingeneral, polymorphism refers to


existence of different forms of a single
entity

► For example, both Diamond and Coal are


different forms of Carbon
Polymorphism in OO Model

► InOO model, polymorphism means that


different objects can behave in different
ways for the same message (stimulus)

► Consequently,sender of a message does


not need to know exact class of the receiver
Example – Polymorphism

draw Shape
View
draw

Line Circle Triangle


draw draw draw
Example – Polymorphism

print File
Editor
print

ASCII File PDF File PS File


print print print
Polymorphism – Advantages
► Messagescan be interpreted in different
ways depending upon the receiver class

draw Shape
View
draw

Line Circle Triangle


draw draw draw
Polymorphism – Advantages
► New classes can be added without changing
the existing model

draw Shape
View
draw

Square Line Circle Triangle


draw draw draw draw
Polymorphism – Advantages

► Ingeneral, polymorphism is a powerful tool


to develop flexible and reusable systems
Object-Oriented Modeling

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

► 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
 Eliminate irrelevant classes

► Editor – Very broad scope

► User – Out of system boundary


…Identify Classes
 Add classes by analyzing requirements

► Group – required to behave as a shape


 “Individual shapes can be grouped together and
can behave as a single shape”

► View – editor must have a display area


…Identify Classes
 Following classes have been identified:

► Shape • Group
► Line • View
► Circle
► Triangle
► Menu
Object Model – Graphic Editor

Shape Group

Line Menu

Circle
View

Triangle
Identify Associations
 Extract verbs connecting objects

• “Individual shapes can be grouped


together”
 Group consists of lines, circles, triangles
 Group can also consists of other groups
(Composition)
… Identify Associations
 Verify access paths

► View contains shapes


 View contains lines
 View contains circles
 View contains triangles
 View contains groups
(Aggregation)
… Identify Associations
 Verify access paths

► Menu sends message to View


(Simple One-Way Association)
Object Model – Graphic Editor

Menu View Shape


nn
nn

nn nn nn
Line nn Circle Triangle Group
nn
nn nn
Identify Attributes
 Extract properties of the object
 From the problem statement

► Properties are not mentioned


…Identify Attributes
 Extract properties of the object
 From the domain knowledge
• Line • Triangle
– Color – Color
– Vertices – Vertices
– Length – Angle
• Circle • Shape
– Color
– Color
– Vertices
– Vertices
– Radius
…Identify Attributes
 Extract properties of the object
 From the domain knowledge
• Group • Menu
– noOfObjects – Name
• View – isOpen
– noOfObjects
– selected
Object Model – Graphic Editor

Menu View Shape


name noOfObjects color
isOpen selected n vertices

n n n
Line n Circle Triangle Group
length radius angle noOfObjects
n
n
n
Identify Operations
 Extract verbs connected with an object

• 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 Operations
 Eliminate irrelevant operations

► Develop – out of system boundary

► Behave – have broad semantics


…Identify Operations
 Following are selected operations:

• 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

 Search “is a kind of” by looking at keywords


like “such as”, “for example”, etc

• “…shapes such as line, circle and triangle …”


– Line, Circle and Triangle inherits from Shape
…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

► In the inheritance hierarchy,


 All attributes are shared
 All associations are shared
 Some operations are shared
 Others are overridden
…Refining the Object Model

 Share associations

► View contains all kind of shapes

► Group consists of all kind of shapes


…Refining the Object Model

 Share attributes

► Shape – Line, Circle, Triangle and Group


 Color, vertices
…Refining the Object Model

 Share operations

► Shape – Line, Circle, Triangle and Group


 Select
 Move
 Rotate
…Refining the Object Model

 Sharethe interface and override


implementation

► Shape – Line, Circle, Triangle and Group


 Draw
View
Menu noOfObjects Shape
selected
name color
isOpen vertices
add()
remove()
open() nn draw() nn
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
rotate()

Line Circle Triangle Group


length radius angle noOfObjects

draw() draw() draw() draw()


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()
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;

aStudent.rollNo = -514; //Error


Object and Class
► Objectis an instantiation of a user defined
type or a class
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;
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);
};

Student aStudent; Error


aStudent.rollNo;
Access specifiers
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
Example
class Student{
private:
char * name; Cannot be accessed outside class
int rollNo;
public:
void setName(char *); Can be
accessed
void setRollNo(int); outside class
...
};
Example
class Student{
...
int rollNo;
public:
void setRollNo(int aNo);
};
int main(){
Student aStudent;
aStudent.SetRollNo(1);
}
Default access specifiers
► When no access specifier is mentioned then
by default the member is considered private
member
Example
class Student class Student
{ {
char * name; private:
int RollNo; char * name;
}; int RollNo;
};
Example
class Student
{
char * name;
int RollNo;
void SetName(char *);
}; Error
Student aStudent;
aStudent.SetName(Ali);
Example
class Student
{
char * name;
int RollNo;
public:
void setName(char *);
};
Student aStudent;
aStudent.SetName(“Ali”);
Overriding Member Functions of
Base Class
► Derived class can override the member
functions of its base class
► To override a function the derived class
simply provides a function with the same
signature as that of its base class
Overriding
Parent
...
Func1

Child
...
Func1
Overriding
class Parent {
public:
void Func1();
void Func1(int);
};

class Child: public Parent {


public:
void Func1();
};
Overloading vs. Overriding
► Overloading is done within the scope of one
class
► Overriding is done in scope of parent and
child
► Overriding within the scope of single class is
error due to duplicate declaration
Overriding
class Parent {
public:
void Func1();
void Func1(); //Error
};
Overriding Member Functions of
Base Class
► Deriveclass can override member function
of base class such that the working of
function is totally changed
Example
class Person{
public:
void Walk();
};
class ParalyzedPerson: public Person{
public:
void Walk();
};
Overriding Member Functions of
Base Class
► Deriveclass can override member function
of base class such that the working of
function is similar to former
implementation
Example
class Person{
char *name;
public:
Person(char *=NULL);
const char *GetName() const;
void Print(){
cout << “Name: ” << name
<< endl;
}
};
Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* aMajor);

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();

Person *pPtr = sPtr;


pPtr->Print();
return 0;
}
Example
Output:

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 Child1:public Parent1


...
Indirect Base Class
►An indirect base class is not explicitly
listed in a derived class's header with
a colon (:)
►It is inherited from two or more levels
up the hierarchy of inheritance

class GrandParent{};
class Parent1:
public GrandParent {};
class Child1:public Parent1{};