Title: Polymorphism Pure Object Oriented Programming
1PolymorphismPure Object Oriented Programming
Lecture 22
2Announcements
LB
- Office Hours next Tuesday, April 4, 2000 will be
from 100 - 200 p.m. instead of 300 - 400 p.m. - On the homework thats due Friday
- Problem 2 requires inheritance!
3Polymorphism
4Scenarios
- 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
5Motivation
- Wed like to be able to manage objects of
different kinds of classes. - Since classes within a class hierarchy often
share common methods and attributes, wed like to
make use of this fact to make our algorithms
simpler.
6Polymorphism Defined
- The ability to take on different forms.
- Manipulate objects of various classes, and invoke
methods on an object without knowing that
objects type.
7A Class Hierarchy
Animal
Dog
Cat
Fish
Mutt
Poodle
Gold
Beta
8A Polymorphic Example
Animal
Dog
MyMutt isoftype Mutt MyAnimal isoftype
Animal MyDog isoftype Dog . . . MyDog lt-
MyMutt MyAnimal lt- MyMutt
Mutt
9Polymorphism Explained
- MyAnimal lt- 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.
10An Illegal Example
- We are able to assign an object of a sub-class
into an object of a super-class as in - MyAnimal lt- MyMutt
- But the reverse is not true. We cant assign a
superclass object into a sub-class object. - MyMutt lt- MyAnimal // illegal
11Method Calls and Polymorphism
- Assume the Dog class inherits the Animal class,
redefining the MakeNoise method. - Consider the following
- MyAnimal lt- MyDog
- MyAnimal.MakeNoise
12Method Calls and Polymorphism
- MyAnimal lt- MyDog
- MyAnimal.MakeNoise
- Different languages handle this differently.
- For simplicity, well assume that MyAnimal
remembers it is actually an object of the Dog
class, so well execute the MakeNoise method in
the Dog class.
13Polymorphism 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).
14Processing 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. . .
15The Banking Class Hierarchy
16A 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.
17Polymorphic 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)
-
18Polymorphic 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 its own set of capabilities
via inheritance (extension, and/or redefinition).
19Example of Polymorphic Banking
- With polymorphism, our main algorithm doesnt
care what kind of account it is processing - sum, amount isoftype Num
- account isoftype Bank_Account
- account_queue isoftype Queue(Bank_Account)
- . . .
- sum lt- 0
- loop
- exitif( account_queue.IsEmpty )
- account_queue.Dequeue( account )
- sum lt- sum account.Get_Balance
- endloop
- print( Sum of the balances is , sum )
20Resolving 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...
21Polymorphism
- This is the magic of polymorphismit keeps
track of family members within the inheritance
hierarchy for you. - Without it, wed have lots of code sprinkled
through out our algorithm choosing among many
options - if( its Checking_Account ) then
- call Checking_Account Calc_Interest
- elseif( its Super_Savings) then
- call Super_Savings Calc_Interest
- elseif( its CD_Account then
- call CD_Account Calc_Interest
- elseif( its NOW_Account ) then
- call NOW_Account Calc_Interest
- . . .
22Summary
- 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, well assume objects remember
what kind of class they really contain, so method
calls are resolved to the original class.
23Questions?
24Pure Object Oriented Programming
25What Have We Discussed?
- Structured programming
- Object-Oriented programming
- Whats left?
- Everything an object
- Lets make a class coordinate activities
26Structured 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).
27An Example
- Lets write an algorithm to simulate a
veterinarians clinic - Maintain a collection of different animals
- Feed, water, talk with and house animals
- Allow owners to bring pets for treatment and
boarding - Well present a menu of options to the user
28A 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
29An 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
30Simulating a Veterinarian Clinic
LB
user interaction
has-a
Boarding Pens (Vector)
Vet Clinic
Owner (user)
has-a
Pet
is-a
is-a
is-a
Rabbit
Dog
Cat
31The Vector Class
Vector
Initialize
InsertElementAt
RemoveElementAt
ElementAt
Size
Contains
IndexOf
IsEmpty
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 lt 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 lt- 1
- loop
- exitif(count gt 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 lt- count 1
- endloop
- print(Pets all fed!)
- endprocedure // FeedPets
37- . . . continue implementation
- AddPet module, etc.
38Vestiges 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?
39Hybrid 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.
40Hybrid Object-Oriented Programming
- Hybrid OO is not just like structured
- Each object maintains its 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)
41Whats Left?
- The Object-Oriented paradigm is state of the art
- Encapsulation
- Reusability/Adaptability
- Polymorphism
- But whats 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 lt 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 lt- 1
- loop
- exitif(count gt 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 lt- 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
49What 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 were doing Pure OO Programming
50Pure 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.
51Windowing with a Mouse
LB
SimpleCalculator
0
Add
0
Clear
0
52Windowing with a Mouse
LB
SimpleCalculator
5
Add
0
Clear
0
53Windowing with a Mouse
LB
SimpleCalculator
5
Add
12
Clear
0
54Windowing with a Mouse
LB
SimpleCalculator
5
Add
12
Clear
0
55Windowing with a Mouse
LB
SimpleCalculator
5
Add
12
Clear
17
56Windowing with a Mouse
LB
SimpleCalculator
5
Add
12
Clear
17
57Windowing with a Mouse
LB
SimpleCalculator
0
Add
0
Clear
0
58Classes
LB
59Typical Operations
LB
Class AddButton inherits Button ... Procedure
Listen // Activated when mouse button
pressed ResultBox.SetContents( TopBox.GetCont
ents BottomBox.GetContents) endprocedure
This type method listens for an event to occur
60Typical Operations
LB
Class ClearButton inherits Button ... Procedure
Listen // Activated when mouse button
pressed TopBox.Clear BottomBox.Clear ResultB
ox.Clear endprocedure
61Typical Operations
LB
Class CalcWindow inherits Window ... Procedure
Initialize // Starts everything
up super.Initialize AddIn(ClearButton) AddIn
(AddButton) AddIn(TopBox) AddIn(BottomBox) A
ddIn(ResultBox) endprocedure
Where the buttons and boxes are located is magic
62Starting it all up
LB
theWindow isoftype CalcWindow theWindow.ShowAt(LOC
X, LOCY)
This code would appear in some kind of special
initiation construct A root class or a startup
main or whatever.
63Windowing with a Mouse
LB
SimpleCalculator
0
Add
0
Clear
0
64A Vehicle Dealership Example
Queue of Vehicles
Dealership
Car
Truck
User/Customer
65Other Pure OO Examples
- Interactive programs
- Graphical, windowed interfaces
- Mac OS, Windows, etc.
- Event-driven programming
- Complex database applications
66Summary 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.
67Summary 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.
68Questions?
69Pseudocode to Java
LB
- class Simple
- public
- Procedure Initialize()
- // PPP
- procedure setValue(newVal isoftype in Num)
- // ppp
- function getValue returnsa Num()
- // PPP
70Pseudocode to Java
LB
- protected
- value isoftype Num
- Procedure Initialize()
- value lt- 0
- endprocedure
- procedure setValue(newVal isoftype in Num)
- value lt- newVal
- endprocedure
- function getValue returnsa Num()
- getValue returns value
- endfunction
- endclass
71Java version
LB
- 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
72Questions?
73(No Transcript)