Polymorphism Pure Object Oriented Programming. Announcements Office Hours next Tuesday, April 4,...
-
Upload
jonas-mason -
Category
Documents
-
view
216 -
download
0
Transcript of Polymorphism Pure Object Oriented Programming. Announcements Office Hours next Tuesday, April 4,...
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
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 Polymorphic Example
Animal
Dog
Mutt
MyMutt isoftype MuttMyAnimal isoftype AnimalMyDog isoftype Dog. . .MyDog <- MyMuttMyAnimal <- 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 <- MyDogMyAnimal.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 BankingWith polymorphism, our main algorithm doesn’t care what
kind of account it is processing
sum, amount isoftype Numaccount isoftype Bank_Accountaccount_queue isoftype Queue(Bank_Account). . .sum <- 0loop
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.
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 CatRabbit
Pet
Owner(user)
is-ais-ais-a
has-a
has-auserinteraction
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
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.Initializeendalgorithm // 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.
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.ClearBottomBox.ClearResultBox.Clear
endprocedure
LB
Typical Operations
Class CalcWindow inherits Window...Procedure Initialize// Starts everything up
super.InitializeAddIn(ClearButton)AddIn(AddButton)AddIn(TopBox)AddIn(BottomBox)AddIn(ResultBox)
endprocedure
Where the buttons and boxesare located is magic
LB
Starting it all up
theWindow isoftype CalcWindowtheWindow.ShowAt(LOCX, LOCY)
This code would appear in somekind of special initiation construct:A root class or a startup main or whatever.
LB
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.
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 versionclass 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