Principles of Object Oriented
Programming (OOP)
Presentation
On
By
Mr. Shibdas Dutta
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
2
Topics to be Covered
•Overview of OOP
•Concepts of OOP
•Principles of OOP
•Why OOP
•Relationships in OOP
•Conclusions
•Questions
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
3
Overview of OOP
OOPhasrootsfrom1960swhenh/w&s/wbecame
increasinglycomplex,andalsoqualityoften
compromised.
Uses“Object”whichinteractswithdesignapplications
andprograms.
Focuseson“data”rather“process”.
Programscomposedof“Object”i.e.“Modules”.
Objectcontainsall“data”tomanipulateitsowndata
structureunlikemodularprogrammingwhichfocusedto
“function”.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
4
Overview of OOP (Contd…)
Collectionof“co-operating”objectrather“sub-routines”.
Eachobjectiscapableofreceivingmessages,
processingdataandsendingmessagestootherobject.
“Object”canbeviewedasanindependent“machine”
withdistinctrole.
Forexample:Smalltalk,Ruby,Simula,Algol,Python,
C++,Javatomentionafew.
Remember,SmalltalkisthefirstOOP.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
5
Concept Of OOP
Fundamental concepts of OOP are as follows:
Class
Object
Instance & Object State
Method
Message Passing
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
6
Class
Isa“blueprint”or“factory”thatdescribesthe“nature”of
“some-thing”
“nature”–isthing’scharacteristics(i.e.‘attributes’,‘fields’
or‘properties’)andbehaviors(i.e.‘thing’scando’and
‘method/features’).
“some-thing”–isthe“Object”itself.
Forexample:theclassDOGwouldconsistsof
characteristicssharedbyalldogs,suchasno.oflegs,
coloretc.andtheabilitytobarkandsitarethebehaviors.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
7
Object
Apatternofaclassi.e.classDOGdefinesall
possibledogsbylistingsthecharacteristicsand
behaviorstheycanhave.
TheobjectLassieisoneparticulardog,with
particularversionsofthecharacteristics.
Obj1-Lassie
Obj2-Labrador
Obj3-Breeder
Class DOG
Legs
Color
Ear
Bark()
Sit()
Walk()
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
8
Instance & Object State
WhenObjectisinruntimeposition,iscalledInstance.
TheLassieobjectisaninstanceoftheDOGclass.
Thesetofallvaluesoftheattributesofaparticularobject
iscalledits“state”.
Forexample:Class.DOG(no_of_Legs,Color,Ear_type);
Obj1.Lassie(‘4’,”Yellow”,”Thin&Long”);
Obj2.Labrador(‘4’,”Green”,”Big”);
Obj3.Breeder(‘4’,”White”,”VerySmall”);
Object State
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
9
Method
Anobject’sability.
Forexample:Lassie,beingadog,hastheabilitytobark,
sobark()isoneofLassie’smethod.
Similarly,sit(),eat()andwalk()arealsomethodsofLassie
object.
Generally,allbehaviorsofobjectshouldberepresented
bymethods()inprogram.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
11
Principles of OOP
Therearemanyopinionsofwhatitmeansfora
developmentsystemsorlanguagestobe“Object
Oriented”.
However,itiswidelyagreethatanylanguagethatclaims
tobeobjectorientedmustatleastsupport:
Encapsulation, Data Abstraction,
Inheritance and Polymorphism.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
12
Encapsulation
Isthehidingofdataimplementationbyrestrictingaccess
to“accessor”and“mutator”.
“accessor”–isamethodto“access”thedata/info.of
objectbyusinggetmethodasfollowingprogram:
( I am using VB.Net since in my opinion it is easier to read and understand positively
)
Public Class Person
Private _fullName As String = "Raymond Lewallen"
Public ReadOnly Property FullName() As String
Get
Return _fullName
End Get
End Property
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
13
Encapsulation (Contd…)
“mutator”–isapublicmethodto“modify”thedata/info.ofanobject
usingsetmethodasfollowingprogram:
Public Class Person
Private _fullName As String = "Raymond Lewallen“
Public Property FullName() As String
Get
Return FullName
End Get
Set(ByVal value As String)
_fullName = value
End Set
End Property
End Class
Thistypeofdataprotectionandimplementationprotectionwithoutbreaking
theothercodethatisusinginrestoftheprogram,iscalledEncapsulation.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
14
Data Abstraction
Itisthesimplestprincipletounderstand.
Isthedevelopmentsofclassesandobjectsrather
implementationsdetails.
Itdenotesa“model”or“view”ofitem(object).
Itisusedtomanagecomplexitybydecomposecomplex
systemintosmallercomponents.
Definition:“Anabstractiondenotestheessential
characteristicsofanobjectthatdistinguishitfromall
otherkindsofobjectandthusprovidedefinedconceptual
boundaries,relativetotheperspectiveoftheviewer”.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
15
Data Abstraction (Contd…)
Public Class Person
Private _heightAs Int
Public Property Height()As Int
Get
Return _height
End Get
Set(ByVal Value As Int)
_height = Value
End Set
End Property
Lets,lookatthiscodeforapersonobject
(“height”,”weight”and“age”asattributes).
Private _weightAs Int
Public Property Weight()As Int
Get
Return _weight
End Get
Set(ByVal Value As Int)
_weight = Value
End Set
End Property
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
16
Data Abstraction (Contd…)
Private _ageAs Int
Public Property Age()As Int
Get
Return _age
End Get
Set(ByVal Value As Int)
_age = Value
End Set
End Property
Public Sub Sit()
// Code that makes the person sit
End Sub
Public Sub Run()
// Code that makes the person run
End Sub
Public Sub Cry()
// Code that make the person cry
End Sub
Public Function CanRead()As Boolean
// Code that determines if the person can read
// and returns a true or false
End Function
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
17
Data Abstraction (Contd…)
So,Ihavecreateasoftwaremodelofapersonobject.
Ihavecreatedanabstracttypeofwhatapersonobjectistous
outsideofthesoftwareworld.
Theabstractpersonisdefinedbytheoperationsthatcanbe
performedonit,andtheinformationwecangetfromitandgivetoit.
Whatdoestheabstractedpersonobjectlookliketothesoftware
worldthatdoesn'thaveaccesstoitsinnerworkings?
Can'treallyseewhatthecodeisthatmakesthepersonrun!!!
So,inshort,dataabstractionisnothingmorethantheimplementationof
anobjectthatcontainsthesameessentialpropertiesandactions,we
canfindintheoriginalobjectwearerepresenting.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
18
Inheritance
Objectscanrelatetoeachotherwitheithera“hasa”,
“usesa”oran“isa”relationship.
“Isa”istheinheritancewayofobjectrelationship.
Forexample,takealibraryinventorysystem.
Lets,AlibrarylendsBook,Magazine,Audiocassette
andMicrofilmtopeople.
Onsomelevel,thesearetreatedthesameduetosomefeatures
shouldbecommonbutarenotidenticalbecauseabookhasan
ISBNandamagazinedoesnotoraudiocassettehasaplaylength
whereasmicrofilmcannotbecheckedoutovernight!!
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
19
Inheritance (Contd…)
Eachoftheselibrary’sloanableassetsshouldberepresented
byitsownclassdefinitionnamed“LibraryAsset”,calleda
superclassorbaseclass.
Allassetsi.e.(Book,Magazine,AudiocassetteandMicrofilm)
aresubclassesorderivedclasses,sotheyinheritbaseclass
characteristics.
Allassetshaveatitle,adateofacquisition,areplacement
costandcheckedoutoravailableforcheckedout.
Letuslookat“LibraryAsset”Baseclass.Thiswillbeusedas
thebaseclassforSubclass“Book”:
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
20
Inheritance (Contd…)
LibraryAsset { }Title
Author
Dt._Of_acquisition
Checked_Out
ISBN
Replacement_Cost
Book { } Magazine { }Audiocassette { }Microfilm { }
Zone Play_Length Film_Color
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
21
Inheritance (Contd…)
Public Class LibraryAsset
Private _titleAs String
Public Property Title()As String
Get
Return _title
End Get
Set(ByVal Value As String)
_title = Value
End Set
End Property
Private _checkedOutAs Boolean
Public Property CheckedOut()As Boolean
Get
Return _checkedOut
End Get
Set(ByVal Value As Boolean)
_checkedOut = Value
End Set
End Property
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
22
Inheritance (Contd…)
Private _dateOfAcquisitionAs DateTime
Public Property DateOfAcquisition()As DateTime
Get
Return _dateOfAcquisition
End Get
Set(ByVal Value As DateTime)
_dateOfAcquisition = Value
End Set
End Property
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
23
Inheritance (Contd…)
Private _replacementCostAs Double
Public Property ReplacementCost()As Double
Get
Return _replacementCost
End Get
Set(ByVal Value As Double)
_replacementCost = Value
End Set
End Property
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
24
Inheritance (Contd…)
Theinheritancerelationshipiscalledthe“isa”relationship.Abook
“isa”LibraryAsset,asaretheother3assets.Lets,lookatthe“Book”
subclass.
Public Class Book
InheritsLibraryAsset
Private _authorAs String
Public Property Author()As String
Get
Return _author
End Get
Set(ByVal Value As String)
_author = Value
End Set
End Property
Private _isbnAs String
Public Property Isbn()As String
Get
Return _isbn
End Get
Set(ByVal Value As String)
_isbn = Value
End Set
End Property
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
25
Inheritance (Contd…)
Now,letscreateaninstanceofthebookclasssowecanrecorda
newbookintothelibraryinventory:
Dim myBook As Book = New Book
myBook.Author= "Sahil Malik"
myBook.CheckedOut= False
myBook.DateOfAcquisition = #2/15/2005#
myBook.Isbn= "0-316-63945-8"
myBook.ReplacementCost= 59.99
myBook.Title= "The Best Ado.Net Book You'll Ever Buy"
Hence,whenwecreateanewbook,wehaveallthepropertiesof
theLibraryAssetclassavailabletousaswell,becauseweinherited
theclass.
“Oneofthemostpowerfulfeaturesofinheritanceistheabilityto
extendcomponentswithoutanyknowledgeofthewayinwhicha
classwasimplemented”.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
26
Polymorphism
Polymorphismmeansonename,manyforms.
Polymorphismmanifestsitselfbyhavingmultiplemethodsallwiththe
samename,butslightydifferentfunctionality.
Thereare2basictypesofpolymorphism.
Overloading,whichisreferredtoascompile-timepolymorphism.
Overridding,alsocalledrun-timepolymorphism.
Formethodoverloading,thecompilerdetermineswhichmethodwill
beexecuted,andthisdecisionismadewhenthecodegets
compiled.
Formethodoverrriding,whichmethodwillbeused,isdeterminedat
runtimebasedonthedynamictypeofanobject.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
27
Polymorphism (Contd…)
Let’s look at some code of LibraryAsset class as following:
// Base class for library assets
Public MustInherit Class LibraryAsset
// Default fine per day for overdue items
Private Const _finePerDay As Double = 1.25
// Due date for an item that has been checked out
Private _dueDate As DateTime
Public Property DueDate()As DateTime
Get
Return _dueDate
End Get
Set(ByVal Value As DateTime)
_dueDate = Value
End Set
End Property
28
Polymorphism (Contd…)
// Calculates the default fine amount for an overdue item
Public OverridableFunction CalculateFineTotal()As Double
Dim daysOverdue As Int = CalculateDaysOverdue()
If daysOverdue > 0 Then
Return daysOverdue * _finePerDay
Else
Return 0.0
End If
End Function
// Calculates how many days overdue for an item being returned
Protected Function CalculateDaysOverdue()As Int
Return DateDiff(DateInterval.Day, _dueDate, DateTime.Now())
End Function
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
29
Polymorphism (Contd…)
// Magazine class that inherits LibraryAsset
Public NotInheritable Class MagazineInherits LibraryAsset
// No Overriding or Overloading of any function of Base
Class in Magazine class
// So, results will come as per Base class function definition
for this Magazine class
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
30
Polymorphism (Contd…)
// Book class that inherits LibraryAsset
Public NotInheritable Class BookInherits LibraryAsset
// This is the CalculateFineTotal() function of the base class.
// This function overrides the base class function, and any call to CalculateFineTotal
from any instantiated Book class will use this function, notthe base class function.
// This type of polymorphismis called overriding.
Public OverridesFunction CalculateFineTotal()As Double
Dim daysOverdue As Int = CalculateDaysOverdue()
If daysOverdue > 0 Then
Return daysOverdue * 0.75
Else
Return 0.0
End If
End Function
End Class
31
Polymorphism (Contd…)
// AudioCassette class that inherits LibraryAsset
Public NotInheritable Class AudioCassetteInherits LibraryAsset
//ThisistheCalculateFineTotal()function(withoutparameter)ofthebaseclass.
//ThisistheCalculateFineTotal(double)function(withparameter)ofthe
audiocassetteclass.
//Thisfunctionoverridesthebaseclassfunction,andanycalltoCalculateFineTotal()
fromanyinstantiatedAudioCassetteClasswillusethisfunction,notthebaseclass
function.
//Thistypeofpolymorphismiscalledoverloadingandoverriding.
Public Overloads OverridesFunction CalculateFineTotal()As Double
Dim daysOverdue As Int = CalculateDaysOverdue()
If daysOverdue > 0 Then
Return daysOverdue * 0.25
Else
Return 0.0
End If
End Function
32
Polymorphism (Contd…)
// This is the CalculateFineTotal() function of the audiocassette class.
// This type of polymorphismis called overloading.
Public OverloadsFunction CalculateFineTotal(ByVal finePerDay As Double)As Double
Dim daysOverdue As Int = CalculateDaysOverdue()
If daysOverdue > 0 AndAlso finePerDay > 0.0 Then
Return daysOverdue * finePerDay
Else
Return 0.0
End If
End Function
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
33
Polymorphism (Contd…)
Nowletslookatsomecodethatcreatesalltheselibraryitemsand
checkstheminandcalculatesourfinesbasedonreturningthem3days
late:
Public Class Demo
Public Sub Go()
// Set the due date to be three days ago
Dim dueDate As DateTime = DateAdd(DateInterval.Day, -3, Now())
ReturnMagazine(dueDate)
ReturnBook(dueDate)
ReturnAudioCassette(dueDate)
End Sub
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
34
Polymorphism (Contd…)
Public Sub ReturnMagazine(ByVal dueDate As DateTime)
Dim myMagazineAs Magazine = New Magazine
myMagazine.DueDate = dueDate
Dim amountDue As Double = myMagazine.CalculateFineTotal()
Console.WriteLine("Magazine: {0}", amountDue.ToString())
End Sub
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
35
Polymorphism (Contd…)
Public Sub ReturnBook(ByVal dueDate As DateTime)
Dim myBookAs Book = New Book
myBook.DueDate = dueDate
Dim amountDue As Double = myBook.CalculateFineTotal()
Console.WriteLine("Book: {0}", amountDue.ToString())
End Sub
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
36
Polymorphism (Contd…)
Public Sub ReturnAudioCassette(ByVal dueDate As DateTime)
Dim myAudioCassetteAs AudioCassette = New AudioCassette
myAudioCassette.DueDate = dueDate
Dim amountDue As Double
amountDue = myAudioCassette.CalculateFineTotal()
Console.WriteLine("AudioCassette1: {0}", amountDue.ToString())
amountDue = myAudioCassette.CalculateFineTotal(3.0)
Console.WriteLine("AudioCassette2: {0}", amountDue.ToString())
End Sub
End Class
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
37
Polymorphism (Contd…)
The output will look like the following:
Magazine: 3.75
Book: 2.25
AudioCassette1: 0.75
AudioCassette2: 9
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
38
Why OOP
Facilitatesteamdevelopment.
Easiertoreusesoftwarecomponentsand
writereusablesoftware.
EasierGUI(GraphicalUserInterface)and
multimediaprogramming.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
39
Relationships in OOP
AdvantagesofObject-Orientedprogramminglanguageiscode
reuse.Thisreusabilityispossibleduetotherelationshipb/wthe
classes.
Objectorientedprogramminggenerallysupport4typesof
relationshipsthatare:inheritance,association,compositionand
aggregation.
Alltheserelationshipisbasedon"is-a"relationship,"has-a"
relationshipand"part-of”relationship.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
Inheritance:
Inheritance is “IS-A” type of relationship.
“IS-A”relationshipisatotallybasedonInheritance,whichcanbe
oftwotypesClassInheritanceorInterfaceInheritance.
Inheritanceisaparent-childrelationshipwherewecreateanew
classbyusingexistingclasscode.Itisjustlikesayingthat“Ais
typeofB”.
Forexampleis“Appleisafruit”,“Ferrariisacar”.
“HODisastaffmemberofcollege”and“Allteachersarestaff
memberofcollege”.Forthisassumptionwecancreatea
“StaffMember”parentclassandinheritthisparentclassin“HOD”
and “Teacher” class.
40
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
Composition:
Composition is a "part-of" relationship.
compositionmeansuseofinstancevariablesthatarereferences
tootherobjects.
Incompositionrelationshipbothentitiesareinterdependentof
eachotherforexample“engineispartofcar”,“heartispartof
body”.
Letustakeanexampleofcarandengine.Engineisapartofeach
carandbotharedependentoneachother.
41
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
Association:
Association is a “has-a” type relationship.
Associationestablishtherelationshipb/wtwoclassesusing
throughtheirobjects.
Associationrelationshipcanbeonetoone,Onetomany,manyto
oneandmanytomany.
Forexamplesupposewehavetwoclassesthenthesetwo
classesaresaidtobe“has-a”relationshipifbothoftheseentities
shareeachother’sobjectforsomeworkandatthesametime
theycanexistswithouteachothersdependencyorbothhavetheir
ownlifetime.
Forexample,EmployeeandManager relationshipinan
organization.
42
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
Aggregation:
One class work as owner
Inassociationthereisnotanyclasses(entity)workasownerbutin
aggregationoneentityworkasowner.
Inaggregationbothentitiesmeetforsomeworkandthenget
separated.
Aggregationisaonewayassociation.
Letustakeanexampleof“Student”and“address”.Eachstudent
musthaveanaddresssorelationshipb/wStudentclassand
Addressclasswillbe“Has-A”typerelationshipbutviceversaisnot
true(itisnotnecessarythateachaddresscontainbyanystudent).
So,Studentworkasownerentity.
This will be a aggregation relationship.
43
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
44
Conclusions
AnOOPprogrammodelsaworldofactiveobjects.
Anobjectmayhaveitsown“memory,”whichmaycontain
otherobjects.
Anobjecthasasetofmethodsthatcanprocess
messagesofcertaintypes.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
45
Conclusions (Contd…)
Amethodcanchangetheobject’sstate,sendmessages
tootherobjects,andcreatenewobjects.
Anobjectbelongstoaparticularclass,andthe
functionalityofeachobjectisdeterminedbyitsclass.
AprogrammercreatesanOOPapplicationbydefining
classes.
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com
46
Questions
Thanks for Patience!!!
?
Company Confidential: Data-Core Systems, Inc. | datacoresystems.com