cs221 - computer science ii polymorphism 1. cs221 - computer science ii polymorphism 2 outline ...

52
CS221 - Computer Science II Polymorphism 1 Polymorphism

Upload: blaze-andrews

Post on 22-Dec-2015

259 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 1

Polymorphism

Page 2: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 2

Outline8 Explanation of polymorphism.8 Using polymorphism to make generic

classes.

Page 3: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 3

Polymorphism

Page 4: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 4

Polymorphism8 Another feature of OOP

– literally “having many forms”8 Object variables in Java are polymorphic8 Object variables can refer to:

– objects or their declared type – AND any objects that are descendants of the

declared type

ClosedShape s = new ClosedShape();s = new ClosedShape(); //legal!s = new Rectangle(); // legal!

Page 5: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 5

Data Type8 object variables have:

– a declared type: Also called the static type.– a dynamic type. What is the actual type of the

pointee at run time or when a particular statement is executed?

8 Method calls are syntactically legal if the method is in the declared type or any ancestor of the declared type

8 The actual method that is executed at runtime is based on the dynamic type– dynamic dispatch

Page 6: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 6

Question 1Consider the following class declarations:public class BoardSpacepublic class Property extends BoardSpacepublic class Street extends Propertypublic class Railroad extends Property

Which of the following statements would cause a syntax error? Assume all classes have a default constructor.

A. Object obj = new Railroad();B. Street s = new BoardSpace();C. BoardSpace b = new Street();D. Railroad r = new Street();E. More than one of these

Page 7: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 7

What’s the Output?ClosedShape s = new ClosedShape(1,2);System.out.println( s.toString() );s = new Rectangle(2, 3, 4, 5);System.out.println( s.toString() );s = new Circle(4, 5, 10);System.out.println( s.toString() );s = new ClosedShape();System.out.println( s.toString() );

Page 8: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 8

Method LookUp8 To determine if a method is legal, the compiler looks in the

class based on the declared type– if it finds it, great; if not; go to the super class and look there– continue until the method is found, or the Object class is reached

and the method was never found. (Compile error)

8 To determine which method is actually executed the run time system– starts with the actual run time class of the object that is calling the

method– search the class for that method– if found, execute it; otherwise, go to the super class and keep

looking– repeat until a version is found

8 Is it possible the runtime system won’t find a method?

Page 9: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 9

Question 2What is output by the code to the right when run?

A. !!live B. !eggeggC. !eggliveD. !!!E. eggegglive

public class Animal{ public String bt(){ return "!"; }}public class Mammal extends Animal{ public String bt(){ return "live"; }}public class Platypus extends Mammal{ public String bt(){ return "egg";}}Animal a1 = new Animal();Animal a2 = new Platypus();Mammal m1 = new Platypus();System.out.print( a1.bt() );System.out.print( a2.bt() );System.out.print( m1.bt() );

Page 10: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 10

Why Bother?8 Polymorphism allows code reuse in another

way (We will explore this next time)8 Inheritance and polymorphism allow

programmers to create generic algorithms

Page 11: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

11

Generic Programming

CS221 - Computer Science II

Polymorphism

Page 12: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Goals• To understand the objective of generic

programming

• To be able to implement generic classes and methods

• To understand the execution of generic methods in the virtual machine

• To know the limitations of generic programming in Java

Page 13: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

CS221 - Computer Science II

Polymorphism 13

Genericity8 One of the goals of OOP is the support of

code reuse to allow more efficient program development

8 If a algorithm is essentially the same, but the code would vary based on the data type, genericity allows only a single version of that code to exist– some languages support genericity via templates– in Java, there are 2 ways of doing this

• polymorphism and the inheritance requirement• generics

Page 14: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Generic Classes• Generic programming: creation of programming constructs

that can be used with many different types

• In Java, achieved with type parameters or with inheritance

• Type parameter example: Java's ArrayList (e.g. ArrayList<String>)

• Inheritance example: LinkedList implemented in Section 15.2 can

store objects of any class

• Generic class: declared with one or more type parameters

• A type parameter for ArrayList denotes the element type: public class ArrayList<E>{ public ArrayList() { . . . } public void add(E element) { . . . }}

Page 15: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Parameters•Can be instantiated with class or interface type:

ArrayList<BankAccount>

ArrayList<Measurable>

•Cannot use a primitive type as a type variable:

ArrayList<double> // Wrong!

•Use corresponding wrapper class instead:

ArrayList<Double>

Page 16: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Parameters• Supplied type replaces type variable in class

interface

• Example: add in ArrayList<BankAccount> has type variable E replaced with BankAccount:

public void add(BankAccount element)

• Contrast with LinkedList.add from Chapter 15:

public void add(Object element)

Page 17: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Parameters Increase SafetyType parameters make generic code safer and easier to read

Impossible to add a String into an ArrayList<BankAccount>

Can add a String into a LinkedList intended to hold bank accounts ArrayList<BankAccount> accounts1 =

new ArrayList<BankAccount>();LinkedList accounts2 = new LinkedList();// Should hold BankAccount objectsaccounts1.add("my savings");// Compile-time erroraccounts2.add("my savings");// Not detected at compile time . . . BankAccount account = (BankAccount)

accounts2.getFirst();// Run-time error

Page 18: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 1

The standard library provides a class HashMap<K, V> with key type K and value type V. Declare a hash map that maps strings to integers.

Answer: HashMap<String, Integer>

Page 19: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 2

The binary search tree class in Chapter 16 is an example of generic programming because you can use it with any classes that implement the Comparable interface. Does it achieve genericity through inheritance or type variables?

Answer: It uses inheritance.

Page 20: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Implementing Generic Classes• Example: simple generic class that stores pairs of

objects such as:

Pair<String, BankAccount> result = new Pair<String, BankAccount>("Harry Hacker",

harrysChecking);

• Methods getFirst and getSecond retrieve first and second values of pair:

String name = result.getFirst();BankAccount account = result.getSecond();

Page 21: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Implementing Generic Classes• Example of use: return two values at the same

time (method returns a Pair)

• Generic Pair class requires two type parameters, one for each element type enclosed in angle brackets:

public class Pair<T, S>

Page 22: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Good Type Variable Names

Type Variable Name Meaning

E Element type in a collection

K Key type in a map

V Value type in a map

T General type

S, U Additional general types

Page 23: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Class Pairpublic class Pair<T, S> { private T first; private S second;

public Pair(T firstElement, S secondElement) { first = firstElement; second = secondElement; } public T getFirst() { return first; } public S getSecond() { return second; } }

Page 24: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Declaring a Generic Class

Big Java by Cay Horstmann

Copyright © 2009 by John Wiley & Sons. All rights reserved.

Page 25: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Continued

Pair.java 1 /** 2 This class collects a pair of elements of different types.

3 */ 4 public class Pair<T, S> 5 { 6 private T first; 7 private S second; 8 9 /** 10 Constructs a pair containing two given elements.

11 @param firstElement the first element

12 @param secondElement the second element

13 */ 14 public Pair(T firstElement, S secondElement) 15 { 16 first = firstElement; 17 second = secondElement; 18 } 19

Page 26: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Pair.java (cont.) 20 /** 21 Gets the first element of this pair.

22 @return the first element

23 */ 24 public T getFirst() { return first; } 25 26 /** 27 Gets the second element of this pair.

28 @return the second element

29 */ 30 public S getSecond() { return second; } 31 32 public String toString() { return "(" + first + ", " + second + ")"; } 33 }

Page 27: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Continued

PairDemo.java

1 public class PairDemo 2 { 3 public static void main(String[] args) 4 { 5 String[] names = { "Tom", "Diana", "Harry" }; 6 Pair<String, Integer> result = firstContaining(names, "a"); 7 System.out.println(result.getFirst()); 8 System.out.println("Expected: Diana"); 9 System.out.println(result.getSecond()); 10 System.out.println("Expected: 1"); 11 } 12

Page 28: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

PairDemo.java (cont.) 13 /** 14 Gets the first String containing a given string, together

15 with its index.

16 @param strings an array of strings

17 @param sub a string

18 @return a pair (strings[i], i) where strings[i] is the first

19 strings[i] containing str, or a pair (null, -1) if there is no

20 match.

21 */ 22 public static Pair<String, Integer> firstContaining( 23 String[] strings, String sub) 24 { 25 for (int i = 0; i < strings.length; i++) 26 { 27 if (strings[i].contains(sub)) 28 { 29 return new Pair<String, Integer>(strings[i], i); 30 }

Continued

Page 29: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

PairDemo.java (cont.)

31 } 32 return new Pair<String, Integer>(null, -1); 33 } 34 }

Program Run:

Diana Expected: Diana 1 Expected: 1

Page 30: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 3

How would you use the generic Pair class to construct a pair of strings "Hello" and "World"?

Answer:

new Pair<String, String>("Hello", "World")

Page 31: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 4

What is the difference between an ArrayList<Pair<String, Integer>> and a Pair<ArrayList<String>, Integer>?

Answer: An ArrayList<Pair<String, Integer>> contains multiple pairs, for example [(Tom, 1), (Harry, 3)]. A Pair<ArrayList<String>, Integer> contains a list of strings and a single integer, such as ([Tom, Harry], 1).

Page 32: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Generic Methods• Generic method: method with a type variable

• Can be defined inside non-generic classes

• Example: Want to declare a method that can print an array of any type:

public class ArrayUtil { /** Prints all elements in an array. @param a the array to print */ public <T> static void print(T[] a) { . . . } . . .}

Page 33: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Generic MethodsOften easier to see how to implement a generic method by starting with a concrete example; e.g. print the elements in an array of strings:

public class ArrayUtil{ public static void print(String[] a) { for (String e : a) System.out.print(e + " "); System.out.println(); } . . .}

Page 34: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Generic Methods•In order to make the method into a generic method:

• Replace String with a type parameter, say E, to denote the element type

• Supply the type parameters between the method's modifiers and return type

public static <E> void print(E[] a) { for (E e : a) System.out.print(e + " "); System.out.println(); }

Page 35: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Generic Methods• When calling a generic method, you need not

instantiate the type variables:

Rectangle[] rectangles = . . .;ArrayUtil.print(rectangles);

• The compiler deduces that E is Rectangle

• You can also define generic methods that are not static

• You can even have generic methods in generic classes

• Cannot replace type variables with primitive types e.g.: cannot use the generic print method to print an array of type int[]

Page 36: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Defining a Generic Method

Page 37: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 5Exactly what does the generic print method print when you pass an array of BankAccount objects containing two bank accounts with zero balances?

Answer: The output depends on the definition of the toString method in the BankAccount class.

Page 38: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 6

Is the getFirst method of the Pair class a generic method?

Answer: No — the method has no type parameters. It is an ordinary method in a generic class.

Page 39: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Constraining Type Variables• Type variables can be constrained with bounds:

public static <E extends Comparable> E min(E[] a) { E smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].compareTo(smallest) < 0) smallest = a[i]; return smallest; }

• Can call min with a String[] array but not with a Rectangle[] array

• Comparable bound necessary for calling compareTo

• Otherwise, min method would not have compiled

Page 40: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Constraining Type Variables• Very occasionally, you need to supply two or more

type bounds: <E extends Comparable & Cloneable>

• extends, when applied to type variables, actually means “extends or implements”

• The bounds can be either classes or interfaces

• Type variable can be replaced with a class or interface type

Page 41: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 7How would you constrain the type parameter for a generic BinarySearchTree class?

Answer:

public class BinarySearchTree<E extends Comparable>

Page 42: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 8Modify the min method to compute the minimum of an array of elements that implements the Measurable interface of Chapter 9.

Answer:

public static <E extends Measurable> E min(E[] a){ E smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].getMeasure() < smallest.getMeasure()) < 0) smallest = a[i]; return smallest;}

Page 43: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Wildcard Types

Name Syntax Meaning

Wildcard with lower bound

? extends B Any subtype of B

Wildcard with higher bound

? super B Any supertype of B

Unbounded wildcard

? Any type

Page 44: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Wildcard Types• public void addAll(LinkedList<? extends E> other) { ListIterator<E> iter = other.listIterator();

while (iter.hasNext()) add(iter.next()); }

• public static <E extends Comparable<E>> E min(E[] a)

• public static <E extends Comparable<? super E>> E min(E[] a)

• static void reverse(List<?> list)

You can think of that declaration as a shorthand for

static void <T> reverse(List<T> list)

Page 45: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Erasure• The virtual machine erases type parameters, replacing them

with their bounds or Objects

• For example, generic class Pair<T, S> turns into the following raw class:

public class Pair {

private Object first; private Object second;

public Pair(Object firstElement, Object secondElement) { first = firstElement; second = secondElement; } public Object getFirst() { return first; } public Object getSecond() { return second; } }

Continued

Page 46: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Erasure• Same process is applied to generic methods:

public static Comparable min(Comparable[] a)

{ Comparable smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].compareTo(smallest) < 0) smallest = a[i];

return smallest;}

Page 47: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Erasure

• Knowing about raw types helps you understand limitations of Java generics

• For example, trying to fill an array with copies of default objects would be wrong:

public static <E> void fillWithDefaults(E[] a) { for (int i = 0; i < a.length; i++) a[i] = new E(); // ERROR }

Page 48: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Erasure• Type erasure yields:

public static void fillWithDefaults(Object[] a) { for (int i = 0; i < a.length; i++) a[i] = new Object(); // Not useful}

• To solve this particular problem, you can supply a default type:public static <E> void fillWithDefaults(E[] a, E defaultValue) { for (int i = 0; i < a.length; i++) a[i] = defaultValue;}

Page 49: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Erasure• You cannot construct an array of a generic type:

public class Stack<E> { private E[] elements; . . . public Stack() { elements = new E[MAX_SIZE]; // Error } }

• Because the array construction expression new E[] would be erased to new Object[]

Page 50: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Type Erasure• One remedy is to use an array list instead:

public class Stack<E> { private ArrayList<E> elements; . . . public Stack() { elements = new ArrayList<E>(); // Ok

} }

Page 51: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 9

What is the erasure of the print method?

Answer:

public static void print(Object[] a) { for (Object e : a) System.out.print(e + " "); System.out.println(); }

Page 52: CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to

Self Check 10Could the Stack example be implemented as follows?

public class Stack<E> { private E[] elements; . . . public Stack() { elements = (E[]) new Object[MAX_SIZE]; } . . . }

Answer: This code compiles (with a warning), but it is a poor technique. In the future, if type erasure no longer happens, the code will be wrong. The cast from Object[] to String[] will cause a class cast exception.