SlideShare a Scribd company logo
1 of 73
Polymorphism
Pure Object Oriented Programming
Announcements
• Office Hours next Tuesday, April 4, 2000 will be
from 1:00 - 2:00 p.m. instead of 3:00 - 4:00 p.m.
• On the homework that’s due Friday
– Problem 2 requires inheritance!
LB
Polymorphism
Scenarios
• A veterinarian's algorithm might have a list of
animals, but each one needs different food or
care… we want ONE information system to track
all of this without complex logic for each
individual kind of animal.
• A car dealership sells many different types of
cars with different features, but each has a price
and quantity in stock.
• A registration system might treat in-state
students differently from out-of-state students,
graduate students differently from
undergraduates, etc.
• A graphical user interface (GUI) e.g. Windows
needs to puts lots of simlar widgets on screen...
LB
Motivation
• We’d like to be able to manage objects
of different kinds of classes.
• Since classes within a class hierarchy
often share common methods and
attributes, we’d like to make use of this
fact to make our algorithms simpler.
Polymorphism Defined
• The ability to take on different forms.
• Manipulate objects of various classes,
and invoke methods on an object
without knowing that object’s type.
A Class Hierarchy
Animal
Dog Cat Fish
Mutt Poodle Gold Beta
A Polymorphic Example
Animal
Dog
Mutt
MyMutt isoftype Mutt
MyAnimal isoftype Animal
MyDog isoftype Dog
. . .
MyDog <- MyMutt
MyAnimal <- MyMutt
Polymorphism Explained
MyAnimal <- MyMutt seems incorrect. The left
and right hand side of the assignment seem to
not match; or do they?
Since Mutt inherits from Dog, and Dog inherits from
Animal, then MyMutt is at all times a Mutt, a Dog,
and an Animal. Thus the assignment statement is
perfectly valid.
This makes logical (“real world”) sense.
An Illegal Example
• We are able to assign an object of a sub-
class into an object of a super-class as in:
MyAnimal <- MyMutt
• But the reverse is not true. We can’t
assign a superclass object into a sub-
class object.
MyMutt <- MyAnimal // illegal
Method Calls and Polymorphism
Assume the Dog class inherits the Animal
class, redefining the “MakeNoise” method.
Consider the following:
MyAnimal <- MyDog
MyAnimal.MakeNoise
Method Calls and Polymorphism
MyAnimal <- MyDog
MyAnimal.MakeNoise
Different languages handle this differently.
For simplicity, we’ll assume that MyAnimal
“remembers” it is actually an object of
the Dog class, so we’ll execute the
MakeNoise method in the Dog class.
Polymorphism vs. Inheritance
• Inheritance is required in order to
achieve polymorphism (we must have
class hierarchies).
– Re-using class definitions via
extension and redefinition
• Polymorphism is not required in order
to achieve inheritance.
– An object of class A acts as an
object of class B (an ancestor to A).
Processing Collections
• One of the main benefits of polymorphism
is the ability to easily process collections.
• We will consider a collection (queue) of
bank accounts in the next example. . .
The Banking Class Hierarchy
Cool Savings
Bank
Account
Savings
Account
Checking
Account
NOW
Account
Money Market
Account
CD Account
A Collection of Bank Accounts
Imagine a bank needs to manage all of the
accounts.
Rather than maintain seven separate queues, one
each for: Bank_Accounts, Savings_Accounts,
Cool_Savings, CD_Accounts,
Checking_Accounts, NOW_accounts, and
Money_Market_Accounts
We can maintain only one queue of Bank Accounts.
Polymorphic Banking
Assume accounts of various kinds:
john_account isoftype Checking_Account
paul_account isoftype Cool_Savings
paul_other_account isoftype CD_Account
george_account isoftype NOW_Account
ringo_account isoftype Money_Market
Then put them all in a single structure:
account_queue isoftype Queue(Bank_Account)
account_queue.Enqueue(john_account)
account_queue.Enqueue(paul_account)
account_queue.Enqueue(paul_other_account)
account_queue.Enqueue(george_account)
account_queue.Enqueue(ringo_account)
Polymorphic Banking
account_queue is polymorphic:
• It is holding accounts of “many forms.”
• Each of the accounts is “within the family”
of the class hierarchy of bank accounts.
• Each one will have it’s own set of
capabilities via inheritance (extension,
and/or redefinition).
Example of Polymorphic Banking
With polymorphism, our main algorithm doesn’t care what
kind of account it is processing
sum, amount isoftype Num
account isoftype Bank_Account
account_queue isoftype Queue(Bank_Account)
. . .
sum <- 0
loop
exitif( account_queue.IsEmpty )
account_queue.Dequeue( account )
sum <- sum + account.Get_Balance
endloop
print( “Sum of the balances is: ”, sum )
Resolving Polymorphic Method Calls
• Different languages do this differently.
• The various kinds of Accounts, though all stored
as a Bank_Account, remember the class
(subclass) of which they are an instance.
• So, calls to Get_Balance() will:
– use the method from class NOW_Account if
the object is an instance of NOW_Account
– use the method from class Money_Market if
the object is an instance of Money_Market
– and so on...
Polymorphism
• This is the “magic” of polymorphism…it keeps
track of family members within the inheritance
hierarchy for you.
• Without it, we’d have lots of code sprinkled
through out our algorithm choosing among many
options:
if( it’s Checking_Account ) then
call Checking_Account Calc_Interest
elseif( it’s Super_Savings) then
call Super_Savings Calc_Interest
elseif( it’s CD_Account then
call CD_Account Calc_Interest
elseif( it’s NOW_Account ) then
call NOW_Account Calc_Interest
. . .
Summary
• Polymorphism allows objects to represent
instances of its own class and any of its
sublcasses.
• Polymorphic collections are useful for managing
objects with common (ancestor) interfaces.
• For our purposes, we’ll assume objects
“remember” what kind of class they really
contain, so method calls are resolved to the
original class.
Questions?
Pure Object Oriented Programming
What Have We Discussed?
• Structured programming
• Object-Oriented programming
What’s left?
• Everything an object…
• Let’s make a class coordinate activities
Structured Programming
• Break down the problem.
• Each module has a well-defined interface
of parameters
• A main algorithm calls and coordinates
the various modules; the main is “in
charge.”
• Persistent data (in the main algorithm) vs.
module data (dies upon module
completion).
An Example
Let’s write an algorithm to simulate a veterinarian’s
clinic…
• Maintain a collection of different animals
• Feed, water, talk with and house animals
• Allow owners to bring pets for treatment and
boarding
• We’ll present a menu of options to the user
A Structured Solution
• Write many record types (cat, dog, rabbit)
• Write the collection records and modules
for each type of pet
• Write many modules allowing for
interactions with the collection
• Write menu and processing modules
• Write main algorithm
An Object-Oriented Solution
• Write class hierarchy with inheritance (pet,
cat, dog, rabbit)
• Write the generic collection class
• Write many modules allowing for
interactions with the collection
• Write menu and processing modules
• Write main algorithm
Simulating a Veterinarian Clinic
Boarding Pens
(Vector)
Vet Clinic
Dog
Cat
Rabbit
Pet
Owner
(user)
is-a
is-a
is-a
has-a
has-a
user
interaction
LB
The Vector Class
Vector
Initialize
InsertElementAt
RemoveElementAt
ElementAt
Size
Contains
IndexOf
IsEmpty
• head
…
algorithm VetClinic
uses Vector, Pet, Cat, Dog, Rabbit
Pens isoftype Vector(Pet)
Pens.Initialize
choice isoftype string
loop
PrintMenu
GetChoice(choice)
exitif (choice = “QUIT”)
ProcessChoice(choice, Pens)
endloop
print(“The Vet Clinic has closed. Goodbye!”)
endalgorithm // VetClinic
procedure PrintMenu
print(“Please enter a choice:”)
print(“ADD a pet”)
print(“REMOVE a pet”)
print(“FEED pets”)
print(“LIST pets”)
...
print(“QUIT”)
endprocedure // PrintMenu
procedure GetChoice(choice isoftype out string)
print(“What would you like to do?”)
read(choice)
endprocedure // GetChoice
LB
procedure ProcessChoice(choice iot in string,
Pens iot in/out Vector(Pet))
if (choice = “ADD”) then
AddPet(Pens)
elseif (choice = “REMOVE”) then
RemovePet(Pens)
elseif (choice = “FEED”) then
FeedPets(Pens)
elseif (choice = “LIST”) then
. . .
endif
endprocedure // ProcessChoice
LB
procedure RemovePet(Pens iot in/out Vector(Pet))
IndexToRemove isoftype num
print(“What is the index of the pet to remove?”)
read(IndexToRemove)
if (IndexToRemove <= Pens.SizeOf) then
Pens.RemoveElementAt(IndexToRemove)
else
print(“ERROR: That index is too high”)
endif
endprocedure // RemovePet
procedure FeedPets(Pens iot in/out Vector(Pet))
count isoftype num
count <- 1
loop
exitif(count > Pens.SizeOf)
// get the next pet in the collection and
// polymorphically call the Eat method on
// that pet (whatever its class)
Pens.ElementAt(count).Eat
count <- count + 1
endloop
print(“Pets all fed!”)
endprocedure // FeedPets
. . . continue implementation
AddPet module, etc.
Vestiges of Structured Programming
• In the previous example (and thus far), we
have used classes and objects in the
conventional structured approach to
algorithms that we have used throughout.
• We have done what is called Hybrid OO:
“the use of OO constructs within the
standard structured paradigm.”
• What is the difference?
Hybrid Object-Oriented Programming
• “Hybrid OO” is like Structured in some
ways:
– Break down the problem.
– One module per sub-problem.
– Each module has one task.
– Each module has a interface of
parameters.
– A main algorithm is “in charge” of
program.
Hybrid Object-Oriented Programming
• “Hybrid OO” is not just like structured:
• Each object maintains it’s own persistent data.
• Uses OO constructs (classes & objects):
– Encapsulate data and methods together
– Support data integrity by protecting data
– Reuse, minimizing recreating code
– Inheritance to ease customization
– Polymorphism to model the world
• Our examples so far show Hybrid OO:
– Structured algorithms, main in charge.
– Use of OO constructs (classes & objects)
What’s Left?
• The Object-Oriented paradigm is state of the art:
– Encapsulation
– Reusability/Adaptability
– Polymorphism
• But what’s left?
– The algorithm itself…
– We still have a main algorithm in control
class VetClinic
uses Vector, Pet, Cat, Dog, Rabbit
public
procedure Initialize
// contract here
protected
Pens isoftype Vector(Pet)
procedure Initialize
Pens.Initialize
DoWork
endprocedure // Initialize
// Still in protected section
procedure DoWork
// contract here – protected method
choice isoftype string
loop
PrintMenu
GetChoice(choice)
exitif (choice = “QUIT”)
ProcessChoice(choice)
endloop
print(“The Vet Clinic has closed.”)
endprocedure // DoWork
// Still in protected section
procedure PrintMenu
// contract here – protected method
print(“Please enter a choice:”)
print(“ADD a pet”)
print(“REMOVE a pet”)
print(“FEED pets”)
. . .
print(“QUIT”)
endprocedure // PrintMenu
procedure GetChoice(choice iot out string)
// contract here – protected method
print(“What would you like to do?”)
read(choice)
endprocedure // GetChoice
// Still in protected section
procedure ProcessChoice(choice iot in string)
// contract here – protected method
if (choice = “ADD”) then
AddPet
elseif (choice = “REMOVE”) then
RemovePet
elseif (choice = “FEED”) then
FeedPets
. . .
endif
endprocedure // ProcessChoice
// Still in protected section
procedure RemovePet
// contract here – protected method
IndexToRemove isoftype num
print(“What is index of the pet to remove?”)
read(IndexToRemove)
if (IndexToRemove <= Pens.Size) then
Pens.RemoveElementAt(IndexToRemove)
else
print(“ERROR: That index is too high”)
endif
endprocedure // RemovePet
// Still in protected section
procedure FeedPets
// contract here – protected method
count isoftype num
count <- 1
loop
exitif(count > Pens.Size)
// get the next pet in the collection and
// polymorphically call the Eat method on
// that pet (whatever its class)
Pens.ElementAt(count).Eat
count <- count + 1
endloop
print(“Pets all fed!”)
endprocedure // FeedPets
// Still in protected section
. . . continue the protected methods
endclass // VetClinic
// --------------------------------------
algorithm VetExample
store isoftype VetClinic
store.Initialize
endalgorithm // VetExample
What Did We Do?
• Everything is an object
• The main algorithm (if it exists at all) simply
creates a VetClinic and calls its Initialize method.
• From there, the VetClinic object coordinates the
system
• Now we’re doing Pure OO Programming
Pure Object Oriented Programming
• There is no main algorithm in charge.
• Control is decentralized among various objects.
• Everything in the program is an object.
• A root class “gets things started.”
• The root class is not “in charge”; instead it
invokes some method, beginning a chain reaction
of objects calling methods provided by other
objects.
• Requires a slightly different way of thinking:
centralized control vs. distributed control.
Windowing with a Mouse
0
0
0
Add
Clear
SimpleCalculator
LB
Windowing with a Mouse
5
0
0
Add
Clear
SimpleCalculator
LB
Windowing with a Mouse
5
12
0
Add
Clear
SimpleCalculator
LB
Windowing with a Mouse
5
12
0
Add
Clear
SimpleCalculator
LB
Windowing with a Mouse
5
12
17
Add
Clear
SimpleCalculator
LB
Windowing with a Mouse
5
12
17
Add
Clear
SimpleCalculator
LB
Windowing with a Mouse
0
0
0
Add
Clear
SimpleCalculator
LB
Classes
Button
Listen
GetName
SetName
•Name
CalcWindow
•ClearButton
•AddButton
•TopBox
•BottomBox
•ResultBox
Initialize
ShowAt
TextBox
•Contents
Clear
GetContents
SetContents Interact
LB
Typical Operations
Class AddButton inherits Button
...
Procedure Listen
// Activated when mouse button pressed
ResultBox.SetContents(
TopBox.GetContents +
BottomBox.GetContents)
endprocedure
This type method “listens”
for an event to occur
LB
Typical Operations
Class ClearButton inherits Button
...
Procedure Listen
// Activated when mouse button pressed
TopBox.Clear
BottomBox.Clear
ResultBox.Clear
endprocedure
LB
Typical Operations
Class CalcWindow inherits Window
...
Procedure Initialize
// Starts everything up
super.Initialize
AddIn(ClearButton)
AddIn(AddButton)
AddIn(TopBox)
AddIn(BottomBox)
AddIn(ResultBox)
endprocedure
Where the buttons and boxes
are located is magic
LB
Starting it all up
theWindow isoftype CalcWindow
theWindow.ShowAt(LOCX, LOCY)
This code would appear in some
kind of special initiation construct:
A root class or a startup main or whatever.
LB
Windowing with a Mouse
0
0
0
Add
Clear
SimpleCalculator
LB
A Vehicle Dealership Example
Queue of Vehicles
Car Truck
Dealership
User/Customer
Other Pure OO Examples
• Interactive programs
• Graphical, windowed interfaces
– Mac OS, Windows, etc.
• Event-driven programming
• Complex database applications
Summary of Structured Programming
• Break down the problem.
• One module per sub-problem.
• Each module has one task.
• Each module has a interface of
parameters.
• A main algorithm is “in charge” of
program.
• Local data dies, must pass back to main.
Summary of Hybrid- vs. Pure-OO
• Hybrid-OO programming means:
– Structured algorithms, main in charge.
– Use of OO constructs (classes-&-
objects)
• Pure-OO or Real-OO programming means:
– No main in charge.
– Decentralized, distributed control.
– Everything is an object.
Questions?
Pseudocode to Java
class Simple
public
Procedure Initialize()
// PPP
procedure setValue(newVal isoftype in Num)
// ppp
function getValue returnsa Num()
// PPP
LB
Pseudocode to Java
protected
value isoftype Num
Procedure Initialize()
value <- 0
endprocedure
procedure setValue(newVal isoftype in Num)
value <- newVal
endprocedure
function getValue returnsa Num()
getValue returns value
endfunction
endclass
LB
Java version
class Simple {
private int value;
// ppp
public void Simple() {
value = 0;
} // Constructor
// ppp
public setValue(int newVal) {
value = newVal;
} // setValue
// ppp
public int getValue() {
return value;
} // getValue
} // Simple
LB
Questions?
cs1311lecture22wdl.ppt

More Related Content

Similar to cs1311lecture22wdl.ppt

General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming ConceptHaris Bin Zahid
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Approaching Patterns How to Apply
Approaching Patterns How to ApplyApproaching Patterns How to Apply
Approaching Patterns How to ApplyLloyd Monteiro
 
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2Yo Halb
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)Scott Wlaschin
 
Learn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfLearn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfDatacademy.ai
 
Oz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptxOz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptxALEJANDROLEONGOVEA
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Elizabeth Smith
 
Machine Learning Innovations
Machine Learning InnovationsMachine Learning Innovations
Machine Learning InnovationsHPCC Systems
 
Build a virtual pet with javascript (april 2017)
Build a virtual pet with javascript (april 2017)Build a virtual pet with javascript (april 2017)
Build a virtual pet with javascript (april 2017)Thinkful
 
Mastering Python lesson 3a
Mastering Python lesson 3aMastering Python lesson 3a
Mastering Python lesson 3aRuth Marvin
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionSamuelAnsong6
 
powerpoint 1-19.pdf
powerpoint 1-19.pdfpowerpoint 1-19.pdf
powerpoint 1-19.pdfJuanPicasso7
 
Predict oscars (5:11)
Predict oscars (5:11)Predict oscars (5:11)
Predict oscars (5:11)Thinkful
 

Similar to cs1311lecture22wdl.ppt (20)

General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming Concept
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Approaching Patterns How to Apply
Approaching Patterns How to ApplyApproaching Patterns How to Apply
Approaching Patterns How to Apply
 
CPP12 - Algorithms
CPP12 - AlgorithmsCPP12 - Algorithms
CPP12 - Algorithms
 
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)
 
Learn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfLearn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdf
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Oz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptxOz_Chap 2_M3_Lesson Slides_Variables.pptx
Oz_Chap 2_M3_Lesson Slides_Variables.pptx
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Machine Learning Innovations
Machine Learning InnovationsMachine Learning Innovations
Machine Learning Innovations
 
Build a virtual pet with javascript (april 2017)
Build a virtual pet with javascript (april 2017)Build a virtual pet with javascript (april 2017)
Build a virtual pet with javascript (april 2017)
 
Mastering Python lesson 3a
Mastering Python lesson 3aMastering Python lesson 3a
Mastering Python lesson 3a
 
Perfect Code
Perfect CodePerfect Code
Perfect Code
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
 
powerpoint 1-19.pdf
powerpoint 1-19.pdfpowerpoint 1-19.pdf
powerpoint 1-19.pdf
 
Predict oscars (5:11)
Predict oscars (5:11)Predict oscars (5:11)
Predict oscars (5:11)
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 

cs1311lecture22wdl.ppt

  • 2. Announcements • Office Hours next Tuesday, April 4, 2000 will be from 1:00 - 2:00 p.m. instead of 3:00 - 4:00 p.m. • On the homework that’s due Friday – Problem 2 requires inheritance! LB
  • 4. Scenarios • A veterinarian's algorithm might have a list of animals, but each one needs different food or care… we want ONE information system to track all of this without complex logic for each individual kind of animal. • A car dealership sells many different types of cars with different features, but each has a price and quantity in stock. • A registration system might treat in-state students differently from out-of-state students, graduate students differently from undergraduates, etc. • A graphical user interface (GUI) e.g. Windows needs to puts lots of simlar widgets on screen... LB
  • 5. Motivation • We’d like to be able to manage objects of different kinds of classes. • Since classes within a class hierarchy often share common methods and attributes, we’d like to make use of this fact to make our algorithms simpler.
  • 6. Polymorphism Defined • The ability to take on different forms. • Manipulate objects of various classes, and invoke methods on an object without knowing that object’s type.
  • 7. A Class Hierarchy Animal Dog Cat Fish Mutt Poodle Gold Beta
  • 8. A Polymorphic Example Animal Dog Mutt MyMutt isoftype Mutt MyAnimal isoftype Animal MyDog isoftype Dog . . . MyDog <- MyMutt MyAnimal <- MyMutt
  • 9. Polymorphism Explained MyAnimal <- MyMutt seems incorrect. The left and right hand side of the assignment seem to not match; or do they? Since Mutt inherits from Dog, and Dog inherits from Animal, then MyMutt is at all times a Mutt, a Dog, and an Animal. Thus the assignment statement is perfectly valid. This makes logical (“real world”) sense.
  • 10. An Illegal Example • We are able to assign an object of a sub- class into an object of a super-class as in: MyAnimal <- MyMutt • But the reverse is not true. We can’t assign a superclass object into a sub- class object. MyMutt <- MyAnimal // illegal
  • 11. Method Calls and Polymorphism Assume the Dog class inherits the Animal class, redefining the “MakeNoise” method. Consider the following: MyAnimal <- MyDog MyAnimal.MakeNoise
  • 12. Method Calls and Polymorphism MyAnimal <- MyDog MyAnimal.MakeNoise Different languages handle this differently. For simplicity, we’ll assume that MyAnimal “remembers” it is actually an object of the Dog class, so we’ll execute the MakeNoise method in the Dog class.
  • 13. Polymorphism vs. Inheritance • Inheritance is required in order to achieve polymorphism (we must have class hierarchies). – Re-using class definitions via extension and redefinition • Polymorphism is not required in order to achieve inheritance. – An object of class A acts as an object of class B (an ancestor to A).
  • 14. Processing Collections • One of the main benefits of polymorphism is the ability to easily process collections. • We will consider a collection (queue) of bank accounts in the next example. . .
  • 15. The Banking Class Hierarchy Cool Savings Bank Account Savings Account Checking Account NOW Account Money Market Account CD Account
  • 16. A Collection of Bank Accounts Imagine a bank needs to manage all of the accounts. Rather than maintain seven separate queues, one each for: Bank_Accounts, Savings_Accounts, Cool_Savings, CD_Accounts, Checking_Accounts, NOW_accounts, and Money_Market_Accounts We can maintain only one queue of Bank Accounts.
  • 17. Polymorphic Banking Assume accounts of various kinds: john_account isoftype Checking_Account paul_account isoftype Cool_Savings paul_other_account isoftype CD_Account george_account isoftype NOW_Account ringo_account isoftype Money_Market Then put them all in a single structure: account_queue isoftype Queue(Bank_Account) account_queue.Enqueue(john_account) account_queue.Enqueue(paul_account) account_queue.Enqueue(paul_other_account) account_queue.Enqueue(george_account) account_queue.Enqueue(ringo_account)
  • 18. Polymorphic Banking account_queue is polymorphic: • It is holding accounts of “many forms.” • Each of the accounts is “within the family” of the class hierarchy of bank accounts. • Each one will have it’s own set of capabilities via inheritance (extension, and/or redefinition).
  • 19. Example of Polymorphic Banking With polymorphism, our main algorithm doesn’t care what kind of account it is processing sum, amount isoftype Num account isoftype Bank_Account account_queue isoftype Queue(Bank_Account) . . . sum <- 0 loop exitif( account_queue.IsEmpty ) account_queue.Dequeue( account ) sum <- sum + account.Get_Balance endloop print( “Sum of the balances is: ”, sum )
  • 20. Resolving Polymorphic Method Calls • Different languages do this differently. • The various kinds of Accounts, though all stored as a Bank_Account, remember the class (subclass) of which they are an instance. • So, calls to Get_Balance() will: – use the method from class NOW_Account if the object is an instance of NOW_Account – use the method from class Money_Market if the object is an instance of Money_Market – and so on...
  • 21. Polymorphism • This is the “magic” of polymorphism…it keeps track of family members within the inheritance hierarchy for you. • Without it, we’d have lots of code sprinkled through out our algorithm choosing among many options: if( it’s Checking_Account ) then call Checking_Account Calc_Interest elseif( it’s Super_Savings) then call Super_Savings Calc_Interest elseif( it’s CD_Account then call CD_Account Calc_Interest elseif( it’s NOW_Account ) then call NOW_Account Calc_Interest . . .
  • 22. Summary • Polymorphism allows objects to represent instances of its own class and any of its sublcasses. • Polymorphic collections are useful for managing objects with common (ancestor) interfaces. • For our purposes, we’ll assume objects “remember” what kind of class they really contain, so method calls are resolved to the original class.
  • 24. Pure Object Oriented Programming
  • 25. What Have We Discussed? • Structured programming • Object-Oriented programming What’s left? • Everything an object… • Let’s make a class coordinate activities
  • 26. Structured Programming • Break down the problem. • Each module has a well-defined interface of parameters • A main algorithm calls and coordinates the various modules; the main is “in charge.” • Persistent data (in the main algorithm) vs. module data (dies upon module completion).
  • 27. An Example Let’s write an algorithm to simulate a veterinarian’s clinic… • Maintain a collection of different animals • Feed, water, talk with and house animals • Allow owners to bring pets for treatment and boarding • We’ll present a menu of options to the user
  • 28. A Structured Solution • Write many record types (cat, dog, rabbit) • Write the collection records and modules for each type of pet • Write many modules allowing for interactions with the collection • Write menu and processing modules • Write main algorithm
  • 29. An Object-Oriented Solution • Write class hierarchy with inheritance (pet, cat, dog, rabbit) • Write the generic collection class • Write many modules allowing for interactions with the collection • Write menu and processing modules • Write main algorithm
  • 30. Simulating a Veterinarian Clinic Boarding Pens (Vector) Vet Clinic Dog Cat Rabbit Pet Owner (user) is-a is-a is-a has-a has-a user interaction LB
  • 32. algorithm VetClinic uses Vector, Pet, Cat, Dog, Rabbit Pens isoftype Vector(Pet) Pens.Initialize choice isoftype string loop PrintMenu GetChoice(choice) exitif (choice = “QUIT”) ProcessChoice(choice, Pens) endloop print(“The Vet Clinic has closed. Goodbye!”) endalgorithm // VetClinic
  • 33. procedure PrintMenu print(“Please enter a choice:”) print(“ADD a pet”) print(“REMOVE a pet”) print(“FEED pets”) print(“LIST pets”) ... print(“QUIT”) endprocedure // PrintMenu procedure GetChoice(choice isoftype out string) print(“What would you like to do?”) read(choice) endprocedure // GetChoice LB
  • 34. procedure ProcessChoice(choice iot in string, Pens iot in/out Vector(Pet)) if (choice = “ADD”) then AddPet(Pens) elseif (choice = “REMOVE”) then RemovePet(Pens) elseif (choice = “FEED”) then FeedPets(Pens) elseif (choice = “LIST”) then . . . endif endprocedure // ProcessChoice LB
  • 35. procedure RemovePet(Pens iot in/out Vector(Pet)) IndexToRemove isoftype num print(“What is the index of the pet to remove?”) read(IndexToRemove) if (IndexToRemove <= Pens.SizeOf) then Pens.RemoveElementAt(IndexToRemove) else print(“ERROR: That index is too high”) endif endprocedure // RemovePet
  • 36. procedure FeedPets(Pens iot in/out Vector(Pet)) count isoftype num count <- 1 loop exitif(count > Pens.SizeOf) // get the next pet in the collection and // polymorphically call the Eat method on // that pet (whatever its class) Pens.ElementAt(count).Eat count <- count + 1 endloop print(“Pets all fed!”) endprocedure // FeedPets
  • 37. . . . continue implementation AddPet module, etc.
  • 38. Vestiges of Structured Programming • In the previous example (and thus far), we have used classes and objects in the conventional structured approach to algorithms that we have used throughout. • We have done what is called Hybrid OO: “the use of OO constructs within the standard structured paradigm.” • What is the difference?
  • 39. Hybrid Object-Oriented Programming • “Hybrid OO” is like Structured in some ways: – Break down the problem. – One module per sub-problem. – Each module has one task. – Each module has a interface of parameters. – A main algorithm is “in charge” of program.
  • 40. Hybrid Object-Oriented Programming • “Hybrid OO” is not just like structured: • Each object maintains it’s own persistent data. • Uses OO constructs (classes & objects): – Encapsulate data and methods together – Support data integrity by protecting data – Reuse, minimizing recreating code – Inheritance to ease customization – Polymorphism to model the world • Our examples so far show Hybrid OO: – Structured algorithms, main in charge. – Use of OO constructs (classes & objects)
  • 41. What’s Left? • The Object-Oriented paradigm is state of the art: – Encapsulation – Reusability/Adaptability – Polymorphism • But what’s left? – The algorithm itself… – We still have a main algorithm in control
  • 42. class VetClinic uses Vector, Pet, Cat, Dog, Rabbit public procedure Initialize // contract here protected Pens isoftype Vector(Pet) procedure Initialize Pens.Initialize DoWork endprocedure // Initialize
  • 43. // Still in protected section procedure DoWork // contract here – protected method choice isoftype string loop PrintMenu GetChoice(choice) exitif (choice = “QUIT”) ProcessChoice(choice) endloop print(“The Vet Clinic has closed.”) endprocedure // DoWork
  • 44. // Still in protected section procedure PrintMenu // contract here – protected method print(“Please enter a choice:”) print(“ADD a pet”) print(“REMOVE a pet”) print(“FEED pets”) . . . print(“QUIT”) endprocedure // PrintMenu procedure GetChoice(choice iot out string) // contract here – protected method print(“What would you like to do?”) read(choice) endprocedure // GetChoice
  • 45. // Still in protected section procedure ProcessChoice(choice iot in string) // contract here – protected method if (choice = “ADD”) then AddPet elseif (choice = “REMOVE”) then RemovePet elseif (choice = “FEED”) then FeedPets . . . endif endprocedure // ProcessChoice
  • 46. // Still in protected section procedure RemovePet // contract here – protected method IndexToRemove isoftype num print(“What is index of the pet to remove?”) read(IndexToRemove) if (IndexToRemove <= Pens.Size) then Pens.RemoveElementAt(IndexToRemove) else print(“ERROR: That index is too high”) endif endprocedure // RemovePet
  • 47. // Still in protected section procedure FeedPets // contract here – protected method count isoftype num count <- 1 loop exitif(count > Pens.Size) // get the next pet in the collection and // polymorphically call the Eat method on // that pet (whatever its class) Pens.ElementAt(count).Eat count <- count + 1 endloop print(“Pets all fed!”) endprocedure // FeedPets
  • 48. // Still in protected section . . . continue the protected methods endclass // VetClinic // -------------------------------------- algorithm VetExample store isoftype VetClinic store.Initialize endalgorithm // VetExample
  • 49. What Did We Do? • Everything is an object • The main algorithm (if it exists at all) simply creates a VetClinic and calls its Initialize method. • From there, the VetClinic object coordinates the system • Now we’re doing Pure OO Programming
  • 50. Pure Object Oriented Programming • There is no main algorithm in charge. • Control is decentralized among various objects. • Everything in the program is an object. • A root class “gets things started.” • The root class is not “in charge”; instead it invokes some method, beginning a chain reaction of objects calling methods provided by other objects. • Requires a slightly different way of thinking: centralized control vs. distributed control.
  • 51. Windowing with a Mouse 0 0 0 Add Clear SimpleCalculator LB
  • 52. Windowing with a Mouse 5 0 0 Add Clear SimpleCalculator LB
  • 53. Windowing with a Mouse 5 12 0 Add Clear SimpleCalculator LB
  • 54. Windowing with a Mouse 5 12 0 Add Clear SimpleCalculator LB
  • 55. Windowing with a Mouse 5 12 17 Add Clear SimpleCalculator LB
  • 56. Windowing with a Mouse 5 12 17 Add Clear SimpleCalculator LB
  • 57. Windowing with a Mouse 0 0 0 Add Clear SimpleCalculator LB
  • 59. Typical Operations Class AddButton inherits Button ... Procedure Listen // Activated when mouse button pressed ResultBox.SetContents( TopBox.GetContents + BottomBox.GetContents) endprocedure This type method “listens” for an event to occur LB
  • 60. Typical Operations Class ClearButton inherits Button ... Procedure Listen // Activated when mouse button pressed TopBox.Clear BottomBox.Clear ResultBox.Clear endprocedure LB
  • 61. Typical Operations Class CalcWindow inherits Window ... Procedure Initialize // Starts everything up super.Initialize AddIn(ClearButton) AddIn(AddButton) AddIn(TopBox) AddIn(BottomBox) AddIn(ResultBox) endprocedure Where the buttons and boxes are located is magic LB
  • 62. Starting it all up theWindow isoftype CalcWindow theWindow.ShowAt(LOCX, LOCY) This code would appear in some kind of special initiation construct: A root class or a startup main or whatever. LB
  • 63. Windowing with a Mouse 0 0 0 Add Clear SimpleCalculator LB
  • 64. A Vehicle Dealership Example Queue of Vehicles Car Truck Dealership User/Customer
  • 65. Other Pure OO Examples • Interactive programs • Graphical, windowed interfaces – Mac OS, Windows, etc. • Event-driven programming • Complex database applications
  • 66. Summary of Structured Programming • Break down the problem. • One module per sub-problem. • Each module has one task. • Each module has a interface of parameters. • A main algorithm is “in charge” of program. • Local data dies, must pass back to main.
  • 67. Summary of Hybrid- vs. Pure-OO • Hybrid-OO programming means: – Structured algorithms, main in charge. – Use of OO constructs (classes-&- objects) • Pure-OO or Real-OO programming means: – No main in charge. – Decentralized, distributed control. – Everything is an object.
  • 69. Pseudocode to Java class Simple public Procedure Initialize() // PPP procedure setValue(newVal isoftype in Num) // ppp function getValue returnsa Num() // PPP LB
  • 70. Pseudocode to Java protected value isoftype Num Procedure Initialize() value <- 0 endprocedure procedure setValue(newVal isoftype in Num) value <- newVal endprocedure function getValue returnsa Num() getValue returns value endfunction endclass LB
  • 71. Java version class Simple { private int value; // ppp public void Simple() { value = 0; } // Constructor // ppp public setValue(int newVal) { value = newVal; } // setValue // ppp public int getValue() { return value; } // getValue } // Simple LB