Top Banner
Polymorp hism
33

Polymorphism

Feb 23, 2016

Download

Documents

aya

Polymorphism. Abstract Classes. Java allows abstract classes use the modifier abstract on a class header to declare an abstract class abstract class Vehicle { … } An abstract class is a placeholder in a class hierarchy that represents a generic concept. Vehicle. Car. Boat. Plane. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Polymorphism

Polymorphism

Page 2: Polymorphism

2

Abstract Classes• Java allows abstract classes

– use the modifier abstract on a class header to declare an abstract class abstract class Vehicle{ … }

• An abstract class is a placeholder in a class hierarchy that represents a generic concept

Vehicle

Car Boat Plane

Page 3: Polymorphism

3

Abstract Class: Example

public abstract class Vehicle{ String name;

public String getName() { return name; } \\ method body

abstract public void move(); \\ no body!

}

An abstract class often contains abstract methods, though it doesn’t have to Abstract methods consist of only methods declarations,

without any method body

Page 4: Polymorphism

4

Abstract Classes• An abstract class often contains abstract methods, though it

doesn’t have to– Abstract methods consist of only methods declarations, without any

method body

• The non-abstract child of an abstract class must override the abstract methods of the parent

• An abstract class cannot be instantiated(why?)

• The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate

Page 5: Polymorphism

5

Recap: References and Inheritance

• An object reference variable can refer to any object instantiated from – its own class, or– any class derived from it by inheritance

• For example, Holiday day;day = new Holiday();…day = new Christmas();

Holiday

Christmas

The assignment of an object of a derived class to a reference

variable of the base class can be considered as a widening

conversion

Page 6: Polymorphism

6

References and Inheritance• Through a given type of reference variable,

we can invoke only the methods defined in that type

Can we do the following statements: day.celebrate(); day.listenToChristmasSongs();

Holiday day;day = new Christmas();

class Holiday{ public void celebrate() {…}}class Christmas extends Holiday{ public void celebrate() {…} public void listenToChristmasSongs() {…}}

Page 7: Polymorphism

7

References and Inheritance• We can “promote” an object back to its

original type through an explicit narrowing cast:

Holiday day = new Christmas();day.celebrate();…

Christmas c = (Christmas) day;c.listenToChristmasSongs();

Question: which celebrate() will be invoked by the line: day.celebrate();

Page 8: Polymorphism

8

Java Interface

• A Java interface is a collection of constants and abstract methods– abstract method: a method header without a

method body; we declare an abstract method using the modifier abstract

– since all methods in an interface are abstract, the abstract modifier is usually left off

• Methods in an interface have public visibility by default

Page 9: Polymorphism

9

Interface: Syntax

public interface Doable{ public static final String NAME;

public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num);}

interface is a reserved word

No method in aninterface has a definition (body)

A semicolon immediatelyfollows each method header

Page 10: Polymorphism

10

Implementing an Interface

• A class formally implements an interface by– stating so in the class header in the implements clause

– a class can implement multiple interfaces: the interfaces are listed in the implements clause, separated by commas

• If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors

Page 11: Polymorphism

11

Implementing Interfaces

public class Something implements Doable{ public void doThis () { // whatever }

public void doThat () { // whatever }

// etc.}

implements is areserved word

Each method listedin Doable is

given a definition

public class ManyThings implements Doable, AnotherDoable

Page 12: Polymorphism

12

Interfaces: Examples from Java Standard Class Library

• The Java Standard Class library defines many interfaces:– the Iterator interface contains methods that allow the user to

move through a collection of objects easily• hasNext(), next(), remove()

– the Comparable interface contains an abstract method called compareTo, which is used to compare two objects

if (obj1.compareTo(obj2) < 0) System.out.println(“obj1 is less than obj2”);

Page 13: Polymorphism

13

Polymorphism via Interfaces• Define a polymorphism reference through interface

– declare a reference variable of an interface type Doable obj;

– the obj reference can be used to point to any object of any class that implements the Doable interface

– the version of doThis depends on the type of object that obj is referring to:

obj.doThis();

Page 14: Polymorphism

14

Interface Hierarchies• Inheritance can be applied to interfaces as well as classes• One interface can be used as the parent of another• The child interface inherits all abstract methods of the parent• A class implementing the child interface must define all

methods from both the parent and child interfaces• Note that class hierarchies and interface hierarchies are

distinct (they do not overlap)

Page 15: 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

Page 16: Polymorphism

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.

Page 17: Polymorphism

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.

Page 18: Polymorphism

A Class Hierarchy

Animal

Dog Cat Fish

Mutt Poodle Gold Beta

Page 19: Polymorphism

A Polymorphic Example

Animal

Dog

Mutt

MyMutt isoftype MuttMyAnimal isoftype AnimalMyDog isoftype Dog. . .MyDog <- MyMuttMyAnimal <- MyMutt

Page 20: Polymorphism

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.

Page 21: Polymorphism

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

Page 22: Polymorphism

Method Calls and Polymorphism

Assume the Dog class inherits the Animal class, redefining the “MakeNoise” method.

Consider the following:

MyAnimal <- MyDogMyAnimal.MakeNoise

Page 23: Polymorphism

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.

Page 24: Polymorphism

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).

Page 25: Polymorphism

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. . .

Page 26: Polymorphism

The Banking Class Hierarchy

Cool Savings

Bank Account

Savings Account

Checking Account

NOW Account

Money Market Account

CD Account

Page 27: Polymorphism

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.

Page 28: Polymorphism

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)

Page 29: Polymorphism

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).

Page 30: Polymorphism

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...

Page 31: Polymorphism

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 . . .

Page 32: Polymorphism

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.

Page 33: Polymorphism

Explain how you would program this