Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve.
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Generics (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
Types in programming languages1 What are types, and why do we need them?
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Peyman Dodangeh Sharif University of Technology Spring 2014.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Subtype Polymorphism, Subtyping vs
CMSC 330: Organization of Programming Languages Java Generics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
CSCE 314 Programming Languages Java Generics II Dr. Hyunyoung Lee 1.
Polymorphism (generics) CSE 331 University of Washington.
Java Type System and Object Model Horstmann ch , 7.7.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION GENERICS/PARAMETRIC POLYMORPHISM Autumn 2011 We We Abstraction.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Subtype Polymorphism, cont. Parametric Polymorphism and Java Generics.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Testing (final thoughts). equals() and hashCode() Important when using Hash-based containers class Duration { public final int min; public final int sec;
Parametric Polymorphism and Java Generics. Today’s Lecture Outline Subtype polymorphism Subtyping vs. subclassing Liskov Substitution Principle (LSP)
Chapter 20 Generic Classes and Methods
Subtype Polymorphism, Subtyping vs
Parametric Polymorphism and Java Generics
Testing, cont., Equality and Identity
CSE 331 Software Design & Implementation
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
Generics (Parametric Polymorphism)
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
CSE 331 Software Design & Implementation
Equality, conclusion Based on material by Michael Ernst, University of Washington.
Generic programming in Java
CSE331 SU Final Simple Summary
CSE 331 Software Design and Implementation
Chapter 19 Generics.
Presentation transcript:

Parametric Polymorphism and Java Generics

Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades All quiz and Exam grades in the LMS All HW grades in the Homework Server Quiz 7 today 2

Exam 2 Topics included in Exam 2 Reasoning about ADTs Exceptions Testing Equality Subtype polymorphism, LSP, Java subtyping, etc. Parametric polymorphism and Java generics Review slides and practice tests on Announcements page 3

Announcements There is a penalty for excessive submissions on the Homework Server 20 submissions: no penalty Over 20: about 1pt for 10 submissions We will waive the penalty on HW5, however, it will apply on HW6 and beyond Fall 15 CSCI 2600, A Milanova 4

Today’s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards Type erasure Java arrays Review questions Fall 15 CSCI 2600, A Milanova 5

Bounded Types Restrict Instantiation by Client interface MyList1 { … } MyList1 can be instantiated with any type. Same as interface MyList1 { … } interface MyList2 { … } MyList2 can be instantiated only with type arguments that are Number or subtype of Number MyList1 // OK MyList2 // what happens here? Fall 15 CSCI 2600, A Milanova (example by Michael Ernst) 6 Upper bound on type argument

Why Bounded Types? Generic code can perform operations permitted by the bound class MyList1 void m(E arg) { arg.intValue();//compile-time error; Object //does not have intValue() } } class MyList2 void m(E arg) { arg.intValue();//OK. Number has intValue() } } Fall 15 CSCI 2600, A Milanova (modified from example by Michael Ernst) 7

Bounded Type Parameters An upper bound, type argument can be SuperType or any of its subtypes A lower bound, type argument can be SubType or any of its supertypes Fall 15 CSCI 2600, A Milanova (modified from slide by Michael Ernst) 8

Generic Method Example: Sorting public static > void sort(List list) { // use of get & T.compareTo // T e1 = l.get(…); // T e2 = l.get(…); // e1.compareTo(e2); … } Fall 15 CSCI 2600, A Milanova (modified from example by Michael Ernst) 9 We can use T.compareTo because T is bounded by Comparable !

Another Generic Method Example public class Collections { … public static void copy(List dst, List src) { for (T t : src) { dst.add(t); } Fall 15 CSCI 2600, A Milanova (modified from example by Michael Ernst) 10 When you want to make a single (often static) method generic in a class, precede its return type by type parameter(s).

Java Wildcards public static void copy(List dst, List src) > void sort(List list) Fall 15 CSCI 2600, A Milanova (modified from a slide by Michael Ernst) 11

Today’s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards Type erasure Java arrays Review questions Fall 15 CSCI 2600, A Milanova 12

Generics and Subtyping Integer is a subtype of Number Is List a subtype of List ? Fall 15 CSCI 2600, A Milanova 13 Number Integer List ?

Use Function Subtyping Rules to Find Out! interface List { boolean add(Number elt); Number get(int index); } interface List { boolean add(Integer elt); Integer get(int index); } Function subtyping: subtype must have supertype parameters and subtype return! 14 List ?

What is the Subtyping Relationship Between List and List Java subtyping is invariant with respect to generics: if A ≠ B, then C has no subtyping relationship with C Thus, List and List are unrelated through subtyping! 15 List

Immutable Lists interface ImmutableList { Number get(int index); } interface ImmutableList { Integer get(int index); } 16 ImmutableList ? Fall 15 CSCI 2600, A Milanova (example due to Michael Ernst)

Write-only Lists interface WriteOnlyList { boolean add(Number elt); } interface WriteOnlyList { boolean add(Integer elt); } Is WriteOnlyList subtype of WriteOnlyList NO! Is WriteOnlyList subtype of WriteOnlyList YES! 17 Fall 15 CSCI 2600, A Milanova (example due to Michael Ernst)

Getting Stuff Out of WriteList interface WriteList { boolean add(Number elt); Number get(int index); } interface WriteList { boolean add(Integer elt); Object get(int index); } Is WriteList subtype of WriteList YES! Contravariant subtyping: because the subtyping relationship between the composites (WriteList is subtype of WriteList ) is the opposite of the subtyping relationship between their type arguments (Integer is subtype of Number) 18

Invariance is Restrictive (Because it Disallows Subtyping) Java solution: wildcards interface Set { // Adds all elements in c to this set // if they are not already present. void addAll(Set c); void addAll(Collection c); } 19 Not good. Can’t have Set s; List l; s.addAll(l); // List & Set unrelated Not good either. Can’t have Set s; List l; s.addAll(l); This is because of invariance: List is a subtype of Collection but Collection is not a subtype of Collection ! Solution: wildcards. ? Is the wildcard.

Java Wildcards A wildcard is essentially an anonymous type variable Use ? if you’d use a type variable exactly once ? appears at use sites of the generic type, not at declaration sites Purpose of the wildcard is to make a library more flexible and easier to use by allowing limited subtyping 20

Using Wildcards class HashSet implements Set { void addAll(Collection c) { // What does this give us about c? // i.e., what can code assume about c? // What operations can code invoke on c? } There is also Intuitively, why makes sense here? Fall 15 CSCI 2600, A Milanova (based on slide due to Michael Ernst) 21 This is use of the parameter type E

Legal Operations on Wildcards Object o; Number n; Integer i; PositiveInteger p; List lei; First, which of these is legal? lei = new ArrayList (); Fall 15 CSCI 2600, A Milanova (slide due to Michael Ernst) 22 Which of these is legal? lei.add(o); lei.add(n); lei.add(i); lei.add(p); lei.add(null); o = lei.get(0); n = lei.get(0); i = lei.get(0); p = lei.get(0);

Legal Operations on Wildcards Object o; Number n; Integer i; PositiveInteger p; List lsi; First, which of these is legal? lsi = new ArrayList (); Fall 15 CSCI 2600, A Milanova (slide due to Michael Ernst) 23 Which of these is legal? lsi.add(o); lsi.add(n); lsi.add(i); lsi.add(p); lsi.add(null); o = lsi.get(0); n = lsi.get(0); i = lsi.get(0); p = lsi.get(0);

How to Use Wildcards PECS: Producer Extends, Consumer Super Use when you get (read) values from a producer Use when you add (write) values into a consumer E.g.: void copy(List dst, List src) Use neither, just, if both add and get Fall 15 CSCI 2600, A Milanova (based on slide by Michael Ernst) 24

Wildcards allow Subtyping for Generics Fall 15 CSCI 2600, A Milanova 25 Object Number Integer List ArrayList List

Today’s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards (briefly) Type erasure Arrays Review problems Fall 15 CSCI 2600, A Milanova 26

Type Erasure All type arguments become Object when compiled Reason: backward compatibility with old bytecode At runtime all generic instantiations have same type List lst1 = new ArrayList (); List lst2 = new ArrayList (); lst1.getClass() == lst2.getClass() // true Cannot use instanceof to find type argument Collection cs = new ArrayList (); if (cs instanceof Collection ) { // compile-time error Must use equals() on elements of generic type 27

Equals for a Generic Class class Node { public boolean equals(Object obj) { if (!(obj instanceof Node )) return false; Node n = (Node ) obj; return this.data().equals(n.data()); } Fall 15 CSCI 2600, A Milanova (modified from slide by Michael Ernst) 28 At runtime, JVM has no knowledge of type argument. Node is same as Node. Instanceof is a compile- time error.

Equals for a Generic Class class Node { public boolean equals(Object obj) { if (!(obj instanceof Node )) { return false; Node n = (Node ) obj; return this.data().equals(n.data()); } Fall 15 CSCI 2600, A Milanova (modified from slide by Michael Ernst) 29 Same here. JVM has no knowledge of type argument. Node will cast to Node. Casting results in a compile-time warning, but not error.

Today’s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards (briefly) Type erasure Arrays Review questions Fall 15 CSCI 2600, A Milanova 30

Arrays and Subtyping Integer is subtype of Number Is Integer[] a subtype of Number[] Use our subtyping rules to find out (Just like with List and List ) Again, the answer is NO! Different answer in Java: in Java Integer[] is a Java subtype Number[] ! The Java subtype is not a true subtype! Known as “problem with Java’s covariant arrays” 31 Number Integer Number[] Integer[] ?

Integer[] is a Java subtype of Number[] Number n;ia = na; //what Number[] na;// happens here? Integer i;Double d = 3.14; Integer[] ia;na = ia; //what? na[0] = n;na[2] = d; //? na[1] = i;i = ia[2]; n = na[0]; i = na[1]; //what happens? ia[0] = n; //what happens? ia[1] = i; n = ia[0]; i = ia[1]; 32

Today’s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards (briefly) Type erasure Arrays Review questions Fall 15 CSCI 2600, A Milanova 33

Prints What? Object d1 = new Duration(10,5); Object d2 = null; System.out.println(d1.equals(d2)); Fall 15 CSCI 2600, A Milanova 34

True or False? Question 2. If there are non-null reference values x, y and z such that x.equals(y) returns false, y.equals(z) returns true and x.equals(z) returns true, then equals is not transitive. Question 3. The consistency property requires that for every non-null x and y, such that x.equals(y) is false, x.hashCode() != y.hashCode(). Question 4. Integer f(String) is a function subtype of Number f(Object). 35

CFG and Def-use Pairs 36 s=0; x=0; x<y x+y<10 5.s=s+x+y6.s=s+x-y; return s; True False True False “Merge” node x=x+3; y=y+2; int f(int y) { 1. int s = 0; int x = 0; 2. while (x<y) { 3. x = x+3; y = y+2; 4. if (x+y<10) 5. s = s+x+y; else 6. s = s+x-y; 7. // end-if } // end-while 8. return s; } Is it possible to cover def-use pair (6,5)?

True of False Specification tests is just another name for black-box tests. Fall 15 CSCI 2600, A Milanova 37

Exceptions void m() {... try { String s = new String("car"); String sub = s.substring(4); // IOOBE } catch (RuntimeException e) { e.printStackTrace(); } // the rest of m } a) catch block catches exception then m proceeds b) exception terminates m and propagates to the caller of m. Fall 15 CSCI 2600, A Milanova 38