Transcript
www.techmentor.co.in www.triumphsys.com
2Object Oriented Programming
04/12/23
3Object Oriented Programming
Objectives & Achievements
04/12/23
• To understand the migration from procedural to object oriented approach
• Get the understanding of the pillars of Object Orientation like :
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Objectives
To be able to contribute to the solution of many problems associated with the development
and quality of software products.
• Experience the Enrichment related to :
• Programmer Productivity
• Software Quality
• Design Issues & Maintainability
Achievements!!
4Object Oriented Programming
Procedural Programming - Combination of programming paradigms Functional Programming - Declarative Programming
– A style of building programs, that expresses the logic of a computation without
implementing prominent control flows
– Iteration as Recursion
– operation to be performed over and over until the base case is reached
Structured Programming
– A style of Imperative Programming with more logical program structure
with Power of Control Flows
Modularized Programming
– Primary focus is to conceal the implementation and only interfaces are
exposed
Pre OO Programming Concepts
04/12/23
5Object Oriented Programming
Modern OO Programming
Combination of programming paradigms
Object Oriented Programming
– Class Based
– Prototype Based
Component Assembly Based Programming
Event Based Programming
Aimed on improving the clarity, modularity, flexibility, maintainability,
development cost / time and overall quality of programming
By making extensive use of every programming paradigm’s fundamental
styles
OO Programming Concepts
04/12/23
6Object Oriented Programming
We are here not to question the abilities of existing programming
styles.
Rather – To extend those abilities to achieve something amazing.
Here – It is important to ensure that
We will not be just C Programmers which are using C++ Compiler.
We will be conforming OO Practices on the road of OO Development.
But somehow, IT IS TRUE that OO Practices and PO Practices are not
Mutually Exclusive
Object Oriented Thought Process
04/12/23
7Object Oriented Programming
OO as a thought process thinks about
We can not at look at C++ or JAVA ---------
Just as a collection of features.
Rather ------------ Some features make no sense in isolation
It is strongly recommended that these concepts will have the
solid impact only when we will be thinking in terms of DESIGN
and not just simply CODING.
Object Oriented Thought Process
04/12/23
Reusability Extendibility Operability Run Time Ability
8Object Oriented Programming
Two helpful tips you might keep in mind when trying to get
yourself into an OOP mindset
Don’t Repeat Yourself
If you write some code, you shouldn't have to repeat that particular code
ever again
Thinking more abstractly and planning a little better
Keep It Simple – Stupid
you should try to write code that accomplishes its goal in the simplest
manner possible
Simpler means fewer possibilities for errors and easier maintenance.
Foundations of OO Mindset
04/12/23
9Object Oriented Programming
This principle has been a key, and a huge success in my years
of Program Development Arena.
Minimize the Complexity – Should be primary objective
Break down the problem into small enough or
understandable enough pieces.
Code base would be more flexible, easier to extend, modify or
re-factor when new requirements arrive.
Code should be Simple and straight forward enough to pin
point the bugs.
Keep It Simple & Stupid
04/12/23
10Object Oriented Programming
Better Abstraction
Control Complexities with Selective Ignorance Approach
Reduce the complexities with Levels of Abstraction
Better Modularity
The breaking up of something complex into manageable pieces
Keep It Simple & Stupid -
04/12/23
Complexity Controlling Principles
11Object Oriented Programming
Levels of Abstraction to reduce the complexities
Hierarchical Abstraction with Better Modularity
04/12/23
Asset Management
Bank Accounts Securities Real Estate
Savings Checking Stock Bond Land Building
12Object Oriented Programming
Single Responsibility Principle – Simplicity Variant
04/12/23
Just because You can, doesn't mean you should
13Object Oriented Programming
Keep your methods simple enough which follows Single
Responsibility Principle.
If U R following OOP, let your class should follow the same
Principle.
There should not be more than one reason for a method /
class to change.
A method / class should have one and only one type of
responsibility.
Single Responsibility Principle
04/12/23
14Object Oriented Programming
Single Responsibility principle :
If you have a class that has more than one reason to change, you
need to split the class into multiple classes, based upon their
responsibility.
Note :
That doesn’t mean that, multiple methods cannot be there in a
single class.
That means, methods in a class should be implemented with a single
purpose
Single Responsibility Principle
04/12/23
15Object Oriented Programming
SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE
OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.
At the most basic level, that means : You should be able to extend a
classes behavior, without modifying it.
Open For Extension
This means that the behavior of the module/class can be extended and we can
make the module behave in new and different ways as the requirements changes,
or to meet the needs of new applications
Closed for Modification
The source code is mostly unavailable or unauthorized for modifications.
Open-Closed Principle – One More Simplicity Variant
04/12/23
16Object Oriented Programming
We should never need to change existing code – class all together
All that we should need –
New functionalities can be introduced
by adding new subclasses
overriding the methods,
or by reusing existing code through delegation
This also prevents you from introducing new bugs in existing code.
Open-Closed Principle
04/12/23
17Object Oriented Programming
Every Logical Move should have a single, unambiguous,
authoritative representation within a system.
When this DRY principle is applied successfully…
A modification of any single element of a system does not require a
change in other logically unrelated elements.
Apply effective Re-Use Mechanisms.
DRY code usually makes large software systems easier to
maintain
(Against – Write Everything Twice)
Don’t Repeat Yourself
04/12/23
18Object Oriented Programming
Making sure we are not trying to solve a problem that
someone else has already figured out
The Open/Closed Principle, which states that "software
entities should be open for extension, but closed for
modification,“ works effectively in practice when DRY is
followed.
Duplication can lead to maintenance nightmares, poor
factoring, and logical contradictions.
Don’t Repeat Yourself
04/12/23
19Object Oriented Programming
Object Oriented Program may be considered as a
Collection of Interacting Objects
Each Object is capable of sending & receiving messages in order to process the
data
Fundamental Concepts of OO Programming
Class
Object
Abstraction
Encapsulation
Inheritance
Polymorphism
Object Orientation
04/12/23
20Object Oriented Programming
POP & OOP
Procedural Approach
Object oriented Approach
Function 1 Function 2
Data
Object 1
Data
Object 3
Data
Object 2
Data
21Object Oriented Programming
What we really do in object-oriented programming is create
new data types
We extend the programming language by adding new data
types specific to your needs
And interestingly, it would be gracefully supported by
Encapsulation.
OO Language Feature
04/12/23
22Object Oriented Programming
Abstraction
Process of focusing on utmost necessary things and ignoring unnecessary
details
Encapsulation
Performing more abstract level to identify state and behavior over
necessicity.
Binding them together as one logical unit to generate Real Life Entity.
In Real Life, entities are tightly coupled with their state and
behavior.
Modeling Abstraction - Encapsulation
04/12/23
23Object Oriented Programming
So if we have an abstraction about an entity and if we want to model that,
Then for modeling abstraction as well as encapsulation
We will create a class
And further we will instantiate that class as an object
OO languages support a keyword for this purpose
class
Information is modeled using
Data Members
Behavior is modeled using
Functional Members - Methods
Modeling Abstraction - Encapsulation
04/12/23
24Object Oriented Programming
Class creates a skeleton for the existence of an Object
Class defines the characteristics for an Object
Characteristics include :
Attributes
Fields or Properties (Represents State of Object)
Behaviors
Methods or Operations (Decides what Object can perform)
Anatomy of Class
04/12/23
CAR
• Mfg_Year• Make• Model• Color
• Start()• Accelerate()• Break()• Turn()
25Object Oriented Programming
Objects are the Building Blocks of an OO ProgramAn Object is an instance of a class
Creating an Object means instantiating the class with some specific
properties :
Identity :
property of an object that distinguishes it from other objects
State :
describes the data stored in the object at particular moment (Values of the
attributes)
Behavior :
describes the methods in the object's interface by which the object can be used
Facts about an Object
04/12/23
26Object Oriented Programming
Object Name Class Name
An Object of class CAR
04/12/23
myCAR : CAR
• Mfg_Year = 2010
• Make = “TATA”
• Model = “Indica Vista”
• Color = “Metalic Grey”
• Engine = “FIAT CRDi”
• Chassis No = “ EQ7ZCR59”
27Object Oriented Programming
Object is an instance of Class
An entity that has well defined structure and behavior
Physical existence of class having characteristics…
State
Behavior
Identity
Responsibility
Concept of Object
28Object Oriented Programming
Current values of all its attributes – State of Object. Attributes can be static or dynamic
Concept of Object
ColorMilageMakePower
SpeedFuel levelAir pressureGear
Static
Dynamic Values of all / some attributes
at any moment defines
the state of the car
How will U Describe a this Car
29Object Oriented Programming
Identity
Identity is that property of an object which distinguishes
it from all other objects
Example: Chasis number of car
Responsibility
Responsibility is the role an object serves within the system
Overall meaning of all behaviors together.
Example: Role of car is to facilitate transportation
Concept of Object
30Object Oriented Programming
Kinds of Relationships
amongst classes
Inheritance
Composition
Aggregation
Association
Dependency
Relationships
04/12/23
Kinds of Relationships
amongst functionalities
Include
Extend
Generalization /
Specialization
31Object Oriented Programming
Relationship Notations
04/12/23
32Object Oriented Programming
Abstraction is the practice of reducing and factoring out the
details so that we can focus on a few concepts at a time
A Selective Ignorance Approach
Abstraction Variants
Data Abstraction
Behavioral Abstraction
Control Abstraction
Abstraction
04/12/23
33Object Oriented Programming
Abstraction of a Person -
04/12/23
From various ViewpointsName – Age – Marital Status – Religion – Income Group – Address - Occupation
Blood Group – Weight - Medical History - Qualifications – Skill Set - Experience
Social Survey Health Care Employment
Name
Age
Marital Status
Religion
Income Group
Address
Occupation
Name
Age
Address
Occupation
Blood Group
Weight
Medical History
Name
Age
Address
Occupation
Qualifications
Skill Set
Experience
34Object Oriented Programming
Encapsulation provides Real World Identity to an Object.
Binds State & Behavior together.
Encapsulation conceals the functional details of a class from
objects that interact.
Implementation is kept hidden and only interface is exposed
for interaction
Encapsulation
04/12/23
35Object Oriented Programming
For example Suppose CAR class has an accelerate method
Code for this method defines exactly how an acceleration occurs.
Fuel is pumped from gas tank and mixed with air in the cylinders, pistons
move causing compression resulting in combustion.
The Driver Object does not need to know these technical details in
order to accelerate the car
Encapsulation also protects the integrity of an object by preventing
users from changing internal data of an object into something
invalid
Encapsulation
04/12/23
36Object Oriented Programming
Encapsulation provides
Implementation Hiding
Specifying the Access Control Qualifiers
– Public
– Private
– Protected
Guaranteed initialization and Clean Up
Constructors
Destructors
Encapsulation
04/12/23
37Object Oriented Programming
Better Abstraction Level – Control Abstraction
04/12/23
class stack {
};
int top;Int stack[ ]
public:
push();pop();
class queue {
};
int rear, front;Int queue[ ];
public:
insert();delete();
stack s1; queue q1;
Any attempt of crossReferencing the methodswill be objected byCompiler itself
Like :
S1.insert(); ORq1.push();
38Object Oriented Programming
Basic approach to accomplish Code Reuse here isDo not recreate the existing class from a scratch
Leaving no scope for further inconsistencies
Use / Extend existing class which is provenDebugged and used several times.
You simply create objects of your existing class inside new class
New class is composed of objects of existing class.COMPOSITION
You create a new class as a type of existing class.Take the basic form of existing class and simply add new code to it and that too, without modifying existing class.INHERITANCE
Influential Reuse Mechanisms in OO Languages
04/12/23
39Object Oriented Programming
Actually we have already been composing the classesPrimarily with Built-In Types.
It turns out to be almost as easy to use compositionWith user defined types, typically with classes.
Composition
04/12/23
class date {
};
class person { char name[20];
};
int dd, mm, yy ; date DOB
40Object Oriented Programming
The syntax of Composition was quite obvious.
Now --------- A new approach to perform Inheritance
Just say ------ “ This New Class is like that Old Class “
New Class : Existing Class
New Class is said to be derived from Existing Class .
Where as Existing Class works as Base Class for New Class.
When we explore like this ----------------- we readily make specific
part of base class accessible to derived class.
Of course ---------- without impacting the protection mechanism of
encapsulation.
Inheritance
04/12/23
41Object Oriented Programming
Inheritance
04/12/23
class person { char name[20];
};
date DOB
class analyst : public emp {
Incetives
};
class date {
};
int dd, mm, yy ;
class emp : public person {
EmpId Salary
};
42Object Oriented Programming
Class Hierarchy and Relationships
04/12/23
Person DateHas - a
Employee
Is - a
Analyst
Is - a
Analyst Analyst
Is - a Is - a
43Object Oriented Programming
04/12/23
44Object Oriented Programming
We should not construct a derived class without calling the base class
constructor.
It either happens implicitly, if it is a Non – Argument Constructor
Mechanism.
The Base Class Constructors are called implicitly in the opening stage of
Derived Class Constructor.
Virtually, the first line of derived class constructor would be the call to the
Base Class Constructor.
For the Parameterized Constructor, it’s other way round. We need to
follow separate mechanism known as “Constructor Chaining”. Here
we specify Constructor’s Initialization List.
Constructors & Parameter List in Inheritance
04/12/23
45Object Oriented Programming
Base Class Access Specifier Gimmicks
04/12/23
Private Members of Base Class
• Can not be inherited• Not accessible for derived class directly• Not accessible for outside environment
Public Members of Base Class
• Directly available for derived class• Accessible for outside environment also.
Protected Members of Base Class
• Directly available for derived class• Not Accessible for outside environment.
46Object Oriented Programming
Inheritance Variants
04/12/23
Class A
Class B
Simple Inheritance
Class B Class C
Class A
Class DClass C
Multilevel Inheritance
Multiple Inheritance
Hybrid Inheritance
Multipath Inheritance
47Object Oriented Programming
Here 3 variants of Inheritance are involved - Simple / Multiple / Multilevel Derived Class D has 2 direct base classes ‘Class B’ & ‘Class C’Which themselves have a common base class ‘Class A’ --- Indirect Base ClassClass D inherits the traits of Indirect Base Class via two separate paths.All Public & Protected Members of Class A are inherited into Class D twice.Class D would have duplicate sets of inherited members from Class A causing ambiguity.This can be avoided by making the common base class as Virtual Base Class
Consequence of Multipath Inheritance
04/12/23
Class B Class C
Class A
Class D
Multipath Inheritance
48Object Oriented Programming
When a class is made a Virtual Base Class, Compiler takes necessary care to see that only one copy of that class is inherited.
Rregardless of how many inheritance paths exist
Virtual Base Class
04/12/23
Class A { …..; };
Class B1 : virtual public A { …..; };
Class B2 : public virtual A { …..; };
Class C : public B1, public B2 { …..; };
49Object Oriented Programming
Class Hierarchy and Relationships
04/12/23
Person Date
Employee
SM Programmer Admin
Empid, Basic
AllowanceProject name, Passport Details, Km, CPK
Target, Commission Passport Details, Km, CPK
50Object Oriented Programming
04/12/23
Media
Print Tape
Title of BookPriceDisplay() -
No of PagesDisplay() – Title, Pages, Price
Play TimeDisplay() – Title – Playtime - Price
51Object Oriented Programming
Making a member variable “static”
For a static Member variable, individual copies of member are not
made for each object.
No matter, how many objects of class are instantiated, only one
copy of static data member exists
All objects of that class will share same variable.
Importantly, when we declare a static data member within a class, we
are not defining it. i.e. not allocating any storage for it.
We need to provide a global definition outside the class. This is done
by re-declaring static variable using ::
Static Members of a Class
04/12/23
top related