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.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
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.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Inheritance. Introduction In real situations either when modeling real world objects such as vehicles, animals, etc. or when modeling abstract data structures.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Class Relationships Composition: A class contains objects of other class(es) (actually, references to such objects) –A “has a” relationship.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 Instructor: Michael Eckmann.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
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 -
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Programming Languages and Paradigms Object-Oriented Programming.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
BCS 2143 Introduction to Object Oriented and Software Development.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Inheritance in Java. RHS – SOC 2 What is inheritance (in Java)? Inheritance is a mechanism for enhancing existing classes What does that mean…? Defining.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
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.
Polymorphi sm. 2 Abstract Classes Java allows abstract classes – use the modifier abstract on a class header to declare an abstract class abstract class.
Instructor: Tasneem Darwish1 University of Palestine Faculty of Applied Engineering and Urban Planning Software Engineering Department Object Oriented.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
More on Polymorphism. Ever have one of those days?
Topic 4 Inheritance.
Some Important topics. Working with Files Working with a file involves three steps: – Open the file – Perform operations on the file – Close the file.
Object Oriented Database By Ashish Kaul References from Professor Lee’s presentations and the Web.
M1G Introduction to Programming 2 5. Completing the program.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Inheritance ndex.html ndex.htmland “Java.
CSE 143 Lecture 13 Inheritance slides created by Ethan Apter
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism.
Overriding Method.
Behavioral Design Patterns
Inheritance in Java.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Week 4 Object-Oriented Programming (1): Inheritance
CS100A Lecture 22 Previous Lecture This Lecture Inheritance
Types of Programming Languages
Interfaces and Inheritance
3 Fundamentals of Object-Oriented Programming
Designing for Inheritance
CSC 205 Java Programming II
Java Programming Language
MSIS 670 Object-Oriented Software Engineering
Polymorphism and access control
Week 6 Object-Oriented Programming (2): Polymorphism
Java – Inheritance.
More About Inheritance & Interfaces
Java Inheritance.
Workshop for Programming And Systems Management Teachers
Polymorphism 2019/4/29.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

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 us to have superior –Encapsulation –Reusability –Adaptability But as of now that may not be quite so apparent. The LinkedList class that we made held a linked list of StudentRecords but to hold anything else it will require some not insignificant amount of modification We need another tool to allow us to make collections that will hold anything!

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.

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 Polymorphism means many or multiple forms. Refers to the ability to tell an object to perform a method without knowing exactly which method is going to get invoked. May initially seem somewhat magical Well, actually it is...

A Class Hierarchy Animal DogCatFish

A Polymorphic Example Animal Dog Dog myDog; myDog = new Dog(); Animal myAnimal; myAnimal = myDog;

Extends Note that when Java uses inheritance the keyword is extends This is because literally making a subclass object in a sense also makes a superclass object!!! Huh? When we say: myDog = new Dog(); the Dog constructor gets called. It, in turn, must call the Animal constructor And here’s the big secret

Everything is an Object! That’s right! There is a class Object already defined When you don’t extend anything by default you extend Object Thus the Animal constructor calls the Object constructor Looking at an object in memory it would look something like this Object Animal Dog myDog Dog Object reference

Polymorphism Explained The rule is very simple A reference can refer to an object which is either –The same type as the reference –Has a superclass of the same type as the reference So all of the following are legal Dog d = new Dog(); Animal a = new Animal(); Object o = new Object; Object Animal Dog Object reference

Dog d; d = new Dog(); Animal a; a = new Dog(); Object o; o = new Dog(); Dog d; d = new Animal(); Animal a; a = new Animal(); Object o; o = new Animal(); Dog d; d = new Object(); Animal a; a = new Object(); Object o; o = new Object(); DogAnimalObject Reference Object Animal Dog Object Animal Dog Object Animal Dog Object Animal Object Animal Object Animal Object REF Could this be some form of Matrix ® ? Dog Animal Object

An Illegal Example We are able to assign an object of a sub-class into an object of a super-class as in: Animal MyAnimal = new Dog(); But the reverse is not true. We can’t assign a superclass object into a sub-class object. Dog MyDog = new Animal(); // illegal All dogs are animals but not all animals are dogs All dogs are animals but not all animals are dogs

Method Calls and Polymorphism Assume the Dog class extends the Animal class, redefining the “makeNoise” method. Consider the following: Animal MyAnimal = new Dog(); MyAnimal.makeNoise(); Note: The Animal reference is referring to a Dog object. And it’s the Dog’s makeNoise method that gets invoked!

Dynamic Binding Very simple rule. No matter what the reference type is, Java will search the object and execute the lowest occurence of a method it finds. class Object has a toString method Assume that both Animal and Dog have overridden the toString method Object toString() Animal toString() Dog toString() Object o Animal a Dog d A Dog Object o.toString(); a.toString(); d.toString();

Dynamic Binding Very simple rule. No matter what the reference type is, Java will search the object and execute the lowest occurrence of a method it finds. class Object has a toString method Even if Animal has no toString method! Object toString() Animal Dog toString() Object o Animal a Dog d A Dog Object o.toString(); a.toString(); d.toString();

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 Objects in the next example... Note: This means we rewrite our Queue class (and all associated classes) to hold Objects.

The Banking Class Hierarchy DeluxeSavings BankAccount SavingsAccount CheckingAccount NOWAccount MoneyMarketAccount CDAccount Object

A Collection of Bank Accounts Imagine a bank needs to manage all of the different types of accounts. Rather than maintain seven separate queues, one each for: BankAccounts, SavingsAccounts, DeluxeSavings, CDAccounts, CheckingAccounts, NOWAccounts, and MoneyMarketAccounts We can maintain only one queue of Objects.

Polymorphic Banking // Assume accounts of various kinds: CheckingAccount johnAaccount; DeluxeSavings paulAccount; CDAccount paulOtherAccount; NOWAccount georgeAccount; MoneyMarket ringoAccount; // Then put them all in a single structure // which is a Queue which holds Objects Queue acctQueue; acctQueue.enqueue(johnAccount); acctQueue.enqueue(paulAccount); acctQueue.enqueue(paulOtherAccount); acctQueue.enqueue(georgeAccount); acctQueue.enqueue(ringoAccount);

Polymorphic Banking accountQueue 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 double sum;... sum = 0.0; while(! acctQueue.isEmpty()) { sum += ((BankAccount)(acctQueue.dequeue())).getBalance(); } System.out.println (“Sum of the balances is: ” + sum );

Resolving Polymorphic Method Calls The Java compiler is our friend Since we said the Queue was a Queue which was written to hold Objects what comes out is an Object reference class Object has no getBalance() method so the compiler would give us a friendly error message politely refuse to compile until we cast the object to a BankAccount object As annoying as this may seem it’s for our own good! Again, Java wants to catch as many problems at compile time to avoid errors at run time!

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 a Checking_Account ) call Checking_Account Calc_Interest else if( it’s a Super_Savings ) call Super_Savings Calc_Interest else if( it’s a CD_Account ) call CD_Account Calc_Interest else if( it’s a NOW_Account ) call NOW_Account Calc_Interest...

Summary Polymorphism allows objects to represent instances of its own class and any of its subclasses. Polymorphic collections are useful for managing objects since all objects are descendants of class Object No matter what the reference type the actual object knows what type it is When there is a choice dynamic binding goes to the lowest level.