Polymorphism

  • Uploaded by: jamesramsden
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Polymorphism as PDF for free.

More details

  • Words: 1,401
  • Pages: 24
1COM0027 Programming 1 Lectures 39-40

Polymorphism Olenka Marczyk

© University of Hertfordshire

Contents • • •

polymorphism static and dynamic types of objects polymorphic • • • •



creation assignment method call parameters

overidding

Reading: Chpt 8.1 - 8.6, Chpt 9.1 - 9.5 10/21/09

Polymorphism So far, we have only ever created variables with the same type as their declared type: Video v1; //declared type v1 = new Video("Matilda","Disney", 94);

However: • Video is a subclass of Item • v1 is of type Video, which is a subtype of Item We can declare a variable to be of one type but assign it to a variable of a subtype (polymorphism) Item p; //declared type p = new Video("Matilda","Disney", 94); 10/21/09

!!!!!

Types of Polymorphism "Polymorphism" - means having different forms Can occur in a range of situations: • Polymorphic data • Polymorphic data structures (collections) • Method polymorphism

10/21/09

Polymorphic Data Polymorphic variables: • a variable stores a reference to an object • the object itself may have different forms In effect, • the variable is declared as having one class • but can store a reference to an object of another class Only allowed if the classes have an inheritance relationship • •

first, we will look at the mechanics of polymorphism then, we will see why polymorphism is useful in design 10/21/09

Static and Dynamic Types A variable has both a static type and a dynamic type ( usually these are the same !!!) •

STATIC TYPE of a variable: • the type (class) given in its declaration • used by COMPILER to check legality of statements



DYNAMIC TYPE of a variable : • the type(class) of object referenced currently • used by RUNTIME SYSTEM during execution

NOTE: modifier static is something completely different !! 10/21/09

Substitution •

an object of one class can replace an object of another class, only if their classes have an inheritance relationship



a subtype can replace a supertype



it can occur in the following situations: • • • •

creation assignment method call parameters

10/21/09

Using static and dynamic types •

the static type of an object variable • is used by the compiler • to check the validity of a method call



the dynamic type of an object variable • is used by the runtime system • to determine which version of a method to execute

10/21/09

Rules for Substitution • A subtype variable can always replace a supertype : • on RHS of a creation statement

e.g. Item p = new Video(...) • on RHS of assignment

e.g

p = v // v is a Video

• as the "calling" object (because it inherits anyway)

e.g. String s = v.getComment() • as a method argument

e.g. myList.add(v) • A supertype variable replacing a subtype must be downcast (AND can't be done in a creation statement) • why would you want to do this ? - explanation later 10/21/09

Polymorphic creation Examples: Item p = new Item("xxx", 100); //ordinary creation // polymorphic creation Item v2 = new Video("Matilda","Disney",94); Item c2 = new CD("Metallica", "Metallica",9,75);

TypeA aaa = new TypeB(…) • • • •

TypeA must be the supertype (parent type) TypeB must be the subtype(child type) TypeB inherits from TypeA a has static type TypeA, but dynamic type TypeB

10/21/09

1

Data Diagram p

Item p; Item v2 = new Video(…)

title playingTime

Item c2 = new CD(…)

gotIt

v2

xxx 100 false

comment c2

title playingTime

The Wall 70 false

gotIt

tracks 10/21/09

Matilda

playingTime

94

gotIt

comment artist

title

Pink Floyd

8

false

comment director

Disney

1

Polymorphic Assignment Video v = new Video(.......) Item p1 = v; v

p1

title

Matilda

playingTime

94

gotIt

false

comment director

Disney

Similar to substitution in basic data types: int x ; double y; y = x BUT x = (int)y

10/21/09

1

Data Diagram Item p; Video v; Item c2; Item p1 = v;

p

title

v

playingTime gotIt

p1

xxx 100 false

comment c2

title playingTime

The Wall 70 false

gotIt

tracks 10/21/09

Matilda

playingTime

94

gotIt

comment artist

title

Pink Floyd

8

false

comment director

Disney

1

Object class •

All classes inherit from Object class



check Object class documentation to see what is available : toString(),equals(),clone()



methods in Object don't always behave in the way you would expect.



it is expected that you will override methods in Object by providing implementation relevant to your classes

10/21/09

1

Java-specific considerations Remember : all classes inherit from Object • Object already has some inheritable methods • you can call these methods on all objects without getting a compilation error • if your class does not override these methods, the system will use the ones in Object • BUT this will not always give results you expect. Having methods with recognisable names makes a class easier to use - but you should provide a class-specific version of them in your class 10/21/09

1

Rules for : System.out.println IF you write : System.out.println(v) //v is a Video THEN it will look in your class for a toString() method IF you have overridden toString() it will use it (even though you have not told it to !!) ELSE it will go up the hierarchy until eventually reaches the toString() in Object •

In Object, toString() returns just class name & reference (e.g. Video@1313906 - NOT the data!!)

10/21/09

1

toString() Recommendation: •

always provide a method returning a String representation of your class • call this method toString() so it overrides the one in Object - everybody expects it • client programmers then don't have to look for it • BUT also be explicit ...println(s.toString()) NOTE: • all basic types (int, double etc.) are handled in an appropriate way without an explicit toString() • many library classes have toString() (EVEN String) 10/21/09

1

Object in ArrayList (1) Object as parameter - can be replaced by an object of any class public boolean add(Object o) private ArrayList uni = new ArrayList(); Student s = new Student(..); uni.add(s); private ArrayList club = new ArrayList(); Member m = new Member(..); club.add(m);

10/21/09

1

Casting •

As with basic types, if you want to assign a supertype to a subtype variable, you must use casting Item v2 = new Video("Matilda","Disney",94); Item c2 = new CD("Metallica","Metallica",9,75); Item p9= new Item("xxx", 100 );



all of these would compile: Item cast to Video Video vv1 = (Video)v2; Video vv2 = (Video)c2; //cast fails at runtime Video vv3 = (Video)p2; //cast fails at runtime

• •

BUT ONLY vv1 would work at runtime because the dynamic type of v2 at this point is Video if you cast, the compiler takes NO responsibility for it !! 10/21/09

1

Object in ArrayList (2) Object as a return value - must be downcast to allow it to be stored

public Object get(int n) Student x = (Student)uni.get(s); Member y = (Member)club(m);

10/21/09

2

DoME Database class Currently Database has 2 ArrayList fields • one for Videos and one for CDs • resulting in a lot of code duplication Re-write code at super class level i.e. for Item private ArrayList items; // need only one method at Item level public void addItem(Item theItem) { items.add(theItem); } 10/21/09

2

Overriding at Runtime If both the supertype and its subtypes have a method with the same signature, overriding ensures that the appropriate version of a method is executed at runtime public void list() { // print list of CDs Iterator iter = items.iterator(); while (iter.hasNext()) // print list of items { Item temp = (Item)iter.next(); video.print(); } } •

works because there is a print() in all classes

10/21/09

2

Overriding Suppose you add the following to the database, in the order shown: p,v,c,p1,p2 list() is executed in the following way:

The runtime system selects the appropriate print() based on the object's dynamic type. 10/21/09

2

Problems remaining •

compiler uses the object's static type for error checking



items from items collection, can only be cast to Item; since we have generally do not know its dynamic type



So, even if we know the dynamic type , we cannot use a subtype method without checking the type THIS TYPE OF CODE SHOULD BE AVOIDED !!!! Item temp = (Item)items.get(i); if (temp instanceof Video) {String s =((Video)temp.getDirector();}

MORE ON HOW TO DO THIS BETTER.. LATER !! 10/21/09

2

Related Documents


More Documents from "curlicue"

Polymorphism
June 2020 9