Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to."— Presentation transcript:

1 CS221 - Computer Science II Polymorphism 1

2 CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to make generic classes.

3 CS221 - Computer Science II Polymorphism 3

4 CS221 - Computer Science II Polymorphism 4  Another feature of OOP –literally “having many forms”  Object variables in Java are polymorphic  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!

5 CS221 - Computer Science II Polymorphism 5 Data Type  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?  Method calls are syntactically legal if the method is in the declared type or any ancestor of the declared type  The actual method that is executed at runtime is based on the dynamic type –dynamic dispatch

6 CS221 - Computer Science II Polymorphism 6 Question 1 Consider the following class declarations: public class BoardSpace public class Property extends BoardSpace public class Street extends Property public 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

7 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() );

8 CS221 - Computer Science II Polymorphism 8 Method LookUp  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)  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  Is it possible the runtime system won’t find a method?

9 CS221 - Computer Science II Polymorphism 9 Question 2 What is output by the code to the right when run? A. !!live B. !eggegg C. !egglive D. !!! 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() );

10 CS221 - Computer Science II Polymorphism 10 Why Bother?  Polymorphism allows code reuse in another way (We will explore this next time)  Inheritance and polymorphism allow programmers to create generic algorithms

11 Generic Programming CS221 - Computer Science II Polymorphism 11

12 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

13 CS221 - Computer Science II Polymorphism 13 Genericity  One of the goals of OOP is the support of code reuse to allow more efficient program development  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

14 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 ) 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 { public ArrayList() {... } public void add(E element) {... } }

15 Type Parameters Can be instantiated with class or interface type: ArrayList Cannot use a primitive type as a type variable: ArrayList // Wrong! Use corresponding wrapper class instead: ArrayList

16 Type Parameters Supplied type replaces type variable in class interface Example: add in ArrayList has type variable E replaced with BankAccount : public void add(BankAccount element) Contrast with LinkedList.add from Chapter 15 : public void add(Object element)

17 Type Parameters Increase Safety Type parameters make generic code safer and easier to read Impossible to add a String into an ArrayList Can add a String into a LinkedList intended to hold bank accounts ArrayList accounts1 = new ArrayList (); LinkedList accounts2 = new LinkedList(); // Should hold BankAccount objects accounts1.add("my savings"); // Compile-time error accounts2.add("my savings"); // Not detected at compile time... BankAccount account = (BankAccount) accounts2.getFirst(); // Run-time error

18 Self Check 1 The standard library provides a class HashMap with key type K and value type V. Declare a hash map that maps strings to integers. Answer: HashMap

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

20 Implementing Generic Classes Example: simple generic class that stores pairs of objects such as: Pair result = new Pair ("Harry Hacker", harrysChecking); Methods getFirst and getSecond retrieve first and second values of pair: String name = result.getFirst(); BankAccount account = result.getSecond();

21 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

22 Good Type Variable Names Type VariableName 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

23 Class Pair public class Pair { 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; } }

24 Declaring a Generic Class Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

25 Continu ed Pair.java 1 /** 2 This class collects a pair of elements of different types. 3 */ 4 public class Pair 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

26 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 }

27 Continu ed PairDemo.java 1 public class PairDemo 2 { 3 public static void main(String[] args) 4 { 5 String[] names = { "Tom", "Diana", "Harry" }; 6 Pair 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

28 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 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 (strings[i], i); 30 } Contin ued

29 PairDemo.java (cont.) 31 } 32 return new Pair (null, -1); 33 } 34 } Program Run : Diana Expected: Diana 1 Expected: 1

30 Self Check 3 How would you use the generic Pair class to construct a pair of strings "Hello" and "World" ? Answer: new Pair ("Hello", "World")

31 Self Check 4 What is the difference between an ArrayList > and a Pair, Integer> ? Answer: An ArrayList > contains multiple pairs, for example [(Tom, 1), (Harry, 3)]. A Pair, Integer> contains a list of strings and a single integer, such as ([Tom, Harry], 1).

32 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 static void print(T[] a) {... } }

33 Generic Methods Often 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(); }... }

34 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 void print(E[] a) { for (E e : a) System.out.print(e + " "); System.out.println(); }

35 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[]

36 Defining a Generic Method

37 Self Check 5 Exactly 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.

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

39 Constraining Type Variables Type variables can be constrained with bounds: public static 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

40 Constraining Type Variables Very occasionally, you need to supply two or more type bounds: 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

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

42 Self Check 8 Modify the min method to compute the minimum of an array of elements that implements the Measurable interface of Chapter 9. Answer: public static 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; }

43 Wildcard Types NameSyntaxMeaning Wildcard with lower bound ? extends B Any subtype of B Wildcard with higher bound ? super B Any supertype of B Unbounded wildcard ? Any type

44 Wildcard Types public void addAll(LinkedList other) { ListIterator iter = other.listIterator(); while (iter.hasNext()) add(iter.next()); } public static > E min(E[] a) static void reverse(List list) You can think of that declaration as a shorthand for static void reverse(List list)

45 Type Erasure The virtual machine erases type parameters, replacing them with their bounds or Object s For example, generic class Pair 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; } } Continu ed

46 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; }

47 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 void fillWithDefaults(E[] a) { for (int i = 0; i < a.length; i++) a[i] = new E(); // ERROR }

48 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 void fillWithDefaults(E[] a, E defaultValue) { for (int i = 0; i < a.length; i++) a[i] = defaultValue; }

49 Type Erasure You cannot construct an array of a generic type: public class Stack { private E[] elements;... public Stack() { elements = new E[MAX_SIZE]; // Error } Because the array construction expression new E[] would be erased to new Object[]

50 Type Erasure One remedy is to use an array list instead: public class Stack { private ArrayList elements;... public Stack() { elements = new ArrayList (); // Ok }

51 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(); }

52 Self Check 10 Could the Stack example be implemented as follows? public class Stack { 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.


Download ppt "CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to."

Similar presentations


Ads by Google