Presentation is loading. Please wait.

Presentation is loading. Please wait.

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 -

Similar presentations


Presentation on theme: "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 -"— Presentation transcript:

1 Polymorphism Pure Object Oriented Programming

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

3 Polymorphism

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 DogCatFish MuttPoodleGoldBeta

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.

23 Questions?

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 has-a user interaction LB

31 The Vector Class Vector Initialize InsertElementAt RemoveElementAt ElementAt Size Contains IndexOf IsEmpty head …

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

58 Classes Button Listen GetName SetName Name CalcWindow ClearButton AddButton TopBox BottomBox ResultBox Initialize ShowAt TextBox Contents Clear GetContents SetContents Interact 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 CarTruck 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.

68 Questions?

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

72 Questions?

73


Download ppt "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 -"

Similar presentations


Ads by Google