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 -

Slides:



Advertisements
Similar presentations
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Object-Oriented PHP (1)
Programming Language Paradigms: summary. Object-oriented programming Objects are the fundamental building blocks of a program. Interaction is structured.
Stéphane Ducasse6.1 Essential Concepts Why OO? What is OO? What are the benefits? What are the KEY concepts? Basis for all the lectures.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 13: Object-Oriented Programming
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
C++ fundamentals.
Searching via Traversals Searching a Binary Search Tree (BST) Binary Search on a Sorted Array Data Structure Conversion and Helper Modules.
Buzzback Inheritance Class Hierarchies Deferred Classes.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Generic Classes Use Cases Inheritance. Generic Classes.
LECTURE 07 Programming using C# Inheritance
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Object Oriented Software Development
Introduction to Object-oriented Programming CSIS 3701: Advanced Object Oriented Programming.
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Introduction to Object-oriented programming and software development Lecture 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and Elizabeth Drake Chapter 8: More About OOP and GUIs.
BCS 2143 Introduction to Object Oriented and Software Development.
Object Oriented Programming Key Features of OO Approach Data encapsulation –data and methods are contained in a single unit, object –promotes internal.
Chapter 8: Writing Graphical User Interfaces
Dec Abstract Classes and Interfaces. Eclipse trick CTRL + D will remove lines Organization Bookmarks TODOs – marking something as //TODO allows.
BIM211 – Visual Programming Objects, Collections, and Events 1.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Guided Notes Ch. 9 ADT and Modules Ch. 10 Object-Oriented Programming PHP support for OOP and Assignment 4 Term project proposal C++ and Java Designer.
1 Object-Oriented Systems Development Bahrami © Irwin/ McGraw-Hill Chapter 2: Object Basics Object-Oriented Systems Development Using the Unified Modeling.
Polymorphi sm. 2 Abstract Classes Java allows abstract classes – use the modifier abstract on a class header to declare an abstract class abstract class.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Object-Oriented Design Simple Program Design Third Edition A Step-by-Step Approach 11.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Class Examples (Simple, Airplane, Queue, Pile) Copy vs. Clone.
Programming in Java CSCI-2220 Object Oriented Programming.
Introduction to Classes and Objects Initializing Objects Making Use of Classes in Algorithms Class Examples.
Microsoft Visual Basic 2008 CHAPTER ELEVEN Multiple Classes and Inheritance.
Review Problems. What is the Big O? i
Lecture 2: Review of Object Orientation. © Lethbridge/La ganière 2005 Chapter 2: Review of Object Orientation What is Object Orientation? Procedural.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Next Back MAP MAP F-1 Management Information Systems for the Information Age Second Canadian Edition Copyright 2004 The McGraw-Hill Companies, Inc. All.
OOP Basics Classes & Methods (c) IDMS/SQL News
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Introduction to Polymorphism. Recall We set out to explore a new language, Java, which uses the Object Oriented Paradigm. We claimed that it would allow.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Object-Orientated Programming
Polymorphism.
Chapter 8: More About OOP and GUIs
Behavioral Design Patterns
Stacks.
CS285 Introduction - Visual Basic
Stacks.
Extended Learning Module G
Workshop for Programming And Systems Management Teachers
Abstraction and Objects
C++ Object Oriented 1.
Presentation transcript:

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

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 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 Add Clear SimpleCalculator LB

Windowing with a Mouse Add Clear SimpleCalculator LB

Windowing with a Mouse Add Clear SimpleCalculator LB

Windowing with a Mouse Add Clear SimpleCalculator LB

Windowing with a Mouse Add Clear SimpleCalculator LB

Windowing with a Mouse Add Clear SimpleCalculator LB

Windowing with a Mouse 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 Add Clear SimpleCalculator LB

A Vehicle Dealership Example Queue of Vehicles CarTruck 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?