24
Department of Mathematics and Computer Science Lecture 1b Polymorphism CSCI 261 Computer Science II

CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

Department of Mathematicsand Computer Science

Lecture 1bPolymorphism

CSCI 261Computer Science II

Page 2: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Roadmap

‣ Problem 1: Code duplication• Re-writing instance variables and methods for each new animal

- Goal: Just write common code once!

- Solved through inheritance: the creation of the Animal superclass

�2

+ display()+ getName()+ speak()

- String name- String quote

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

Page 3: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Roadmap (Cont.)

‣ Problem 2: Hard to update code• Examples:

- Adding a weight for all animals later

- Updating the way a common method, display(), prints an Animal's report

• Goal: Want to make code updates in one place!- Also solved through inheritance

�3

- display()- getName()- getWeight()- speak()

- String name- String quote- double weight

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

Page 4: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Roadmap (Cont.)

‣ Problem 3: Hard to extend code• Still has an ArrayList<Cows> and an ArrayList<Birds>

• Still has an add method for each type of animal: addCow(), addBird()

• exciteAll() and summary() still have to loop through both lists separately

• (How to adding Goats to Farm?)

‣ We will solve through:polymorphism

�4

+ addCow(Cow c)+ addBird(Bird b)+ exciteAll()+ summary()

- ArrayList<Cow> cows- ArrayList<Bird> birds

Farm

+ display()+ getName()+ speak()

- String name- String quote

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

Still haven’t solved this

Page 5: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

What about Farm? (Still Lots of Duplications!)

�5

public class Farm {

private ArrayList<Cow> cows; private ArrayList<Bird> birds;

public Farm() { this.cows = new ArrayList<>(); this.birds = new ArrayList<>(); }

public void addCow(Cow newCow) { this.cows.add(newCow); } public void addBird(Bird newBird) { this.birds.add(newBird); }

public void exciteAll() { for (int i = 0; i < cows.size(); i++) { this.cows.get(i).speak(); }

for (int i = 0; i < birds.size(); i++) { this.birds.get(i).speak(); } }

public void summary() { System.out.println("-------------"); System.out.println("Farm Summary"); System.out.println("-------------"); //display cows int numAnimals = 1; for (int i = 0; i < cows.size(); i++) { System.out.println("# " + numAnimals); this.cows.get(i).display(); System.out.println(); numAnimals++; }

//display birds for (int i = 0; i < birds.size(); i++) { System.out.println("# " + numAnimals); this.birds.get(i).display(); System.out.println(); numAnimals++; } }}

Page 6: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Outline

‣ Subtyping• Polymorphic Variables

• The instanceof Operator

• The Object Class

‣ Polymorphic Methods• Overriding Methods

• The super Reference Revisited (in Methods)

• Dynamic Dispatch

‣ Conclusion

�6

Page 7: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

‣ Our current understanding of object variables:• A Cow variable is a “box” that can store any Cow object

• Let's say that the Cow box’s shape looks like:

‣ Example:

Object Variables: Think “Boxes”

�7

Cow c1, c2;

null null

c1 c2

Page 8: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

‣ Our current understanding of object variables:• A Cow variable is a “box” that can store any Cow object

• Let's say that the Cow box’s shape looks like:

‣ Example:

Object Variables: Think “Boxes”

�8

Cow c1, c2;c1 = new Cow();

c1 c2

null

name: "Bessie"quote: "Moo"

Page 9: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

‣ Our current understanding of object variables:• A Cow variable is a “box” that can store any Cow object

• Let's say that the Cow box’s shape looks like:

‣ Example:

Object Variables: Think “Boxes”

�9

Cow c1, c2;c1 = new Cow();c2 = new Cow("Tuffy", "Mewww");

c1 c2

name: "Tuffy"quote: "Mew"

name: "Bessie"quote: "Moo"

Page 10: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

‣ Our current understanding of object variables:• A Cow variable is a “box” that can store any Cow object

• Let's say that the Cow box’s shape looks like:

‣ Example:

Object Variables: Think “Boxes”

�10

Cow c1, c2;c1 = new Cow();c2 = new Cow("Tuffy", "Mewww");c1 = c2;

c1

c2

name: "Tuffy"quote: "Mew"

Page 11: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

‣ Our current understanding of object variables:• A Cow variable is a “box” that can store any Cow object

• Let's say that the Cow box’s shape looks like:

‣ Example:

Object Variables: Think “Boxes”

�11

Cow c1, c2;c1 = new Cow();c2 = new Cow("Tuffy", "Mewww");c1 = c2;c2 = null;

c1

c2

null

Page 12: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Subtyping and Polymorphism

‣ Subtypes: an object of a subclass is also an object of its superclass• e.g., Cows and Birds are subtypes of the Animal class

‣ Important: Object variables (i.e., “boxes”) may hold objects…• Of their declared type, or

• Of any of their subtype

�12

+ display()+ getName()+ speak()

- String name- String quote

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

Page 13: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Subtyping and Polymorphism

�13

Cow Type Bird Type others...

‣ Important: Object variables may hold objects of their declared typeor of any subtype.

‣ What's the "shape" of the Animal box?

Page 14: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Subtyping and Polymorphism

‣ Important: Object variables may hold objects of their declared typeor of any subtype.

‣ What's the "shape" of the Animal box?

�14

Bird Type others...

Animal Type(merge all subclass boxes!)

Page 15: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Subtyping and Polymorphism

‣ Important: Object variables may hold objects of their declared typeor of any subtype.

‣ What's the "shape" of the Animal box?

�15

others...

Animal Type(merge all subclass boxes!)

Page 16: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Subtyping and Polymorphism

‣ Important: Object variables may hold objects of their declared typeor of any subtype.

‣ What's the "shape" of the Animal box?

�16

Animal Type(merge all subclass boxes!)

Page 17: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Subtyping and Polymorphism

‣ Polymorphism literally means “many shapes”• What's the "shape" of the Animal box? Take all subtypes, merge their

boxes together.

�17

+ display()+ getName()+ speak()

- String name- String quote

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

Behold! The polymorphic(and generic) Animal type!

Page 18: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

‣ Java supports subtypes via Polymorphic Variables (many shapes)

Polymorphic Variables (Important!)

�18

Bird b1 = new Bird(); // We always knew this works. Store the Bird object in a // Bird variable

Bird b1(Bird variable stores a Bird object)

Page 19: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Object Substitution

‣ Java supports subtypes via Polymorphic Variables (many shapes)

�19

Bird b1 = new Bird(); // We always knew this works. Store the Bird object in a // Bird variable

Animal b2 = new Bird(); // THIS WORKS TOO! A Bird object stored in an Animal // variable. This is called substitution.

(Animal variable can also store a Bird due to subtyping)

Animal b2

Bird b1(Bird variable stores a Bird object)

Page 20: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Does Reverse Substitution Work?

‣ Does the reverse work?• Remember that inheritance is a one-way street.

‣ Analogy:• We "molded" a box to store Birds.

• It cannot be re-molded to store something more generic.

�20

Bird daffy = new Animal(); // The Bird box is more specialized than what // you're trying to store inside it!

+ display()+ getName()+ speak()

- String name- String quote

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

Less refined

More refined

Page 21: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Sanity Check: Polymorphic Variables

‣ Given the class hierarchy, which of the following assignments are valid?

UgradStudent s4;s4 = new AssocStudent();s4 = new BachelorStuent();s4 = new DentalStudent();

�21

Student s1 = new DoctoralStudent();

PhDStudent s3 = new GradStudent();

GradStudent s2 = new PhDStudent();

Student

UgradStudent GradStudent

MasterStudent DoctoralStudent

PhDStudent DentalStudent MedStudent

AssocStudent BachelorStudent

DentalStudent s5 = new MedStudent();

Less refined

More refined

Page 22: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Trickier Still: Polymorphic Variables

‣ Given the class hierarchy, which of the following assignments are valid?

Student s;GradStudent g1 = new GradStudent();GradStudent g2;s = g1;g2 = s; //won't compile, but shouldn't it?

g2 = (GradStudent) s; //need to down-cast

Student

UgradStudent GradStudent

MasterStudent DoctoralStudent

PhDStudent DentalStudent MedStudent

AssocStudent BachelorStudent

�22

Page 23: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Trickier Still: Polymorphic Variables

‣ Given the class hierarchy, which of the following assignments are valid?

�23

GradStudent g;MasterStudent m;DoctoralStudent d;m = new MasterStudent();g = m;d = (DoctoralStudent) m;

d = (DoctoralStudent) g;

//won't compile, they don't share //subtype-supertype relationship!

//compiles, but runtime error when trying to call DoctoralStudent methods!

Student

UgradStudent GradStudent

MasterStudent DoctoralStudent

PhDStudent DentalStudent MedStudent

AssocStudent BachelorStudent

Page 24: CSCI 261 Computer Science II - cs.pugetsound.educs.pugetsound.edu/~dchiu/cs261/notes/CS261_1b-polymorphism_1.pdf · CSCI 261: Computer Science II - 1b - Polymorphism Subtyping and

CSCI 261: Computer Science II - 1b - Polymorphism

Fixing Problem 3 with Polymorphism!

‣ Problem 3: Hard to extend code• Farm now has a single ArrayList<Animal>

• Farm has a single method for all types of animals: addAnimal()

• exciteAll() and summary() are vastly simplified

• Introduce another animal type now requires no change to Farm class!

‣ Insight: Animal is a polymorphic type!

‣ [Update our Farm code now!]

�24

+ display()+ getName()+ speak()

- String name- String quote

Animal

+ milk()

- double gallonsMilkedCow

+ layEgg()

- int eggsBird

+ addAnimal()+ exciteAll()+ summary()

- ArrayList<Animal> animalsFarm