CSCE 314 Programming Languages

Similar documents
CSCE 314 Programming Languages. Final Review Part II. Dr. Hyunyoung Lee

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

CSE 331 Software Design & Implementation

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

Exercise 8 Parametric polymorphism November 18, 2016

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping

JAVA V Assertions Java, winter semester

Parametric polymorphism and Generics

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS108, Stanford Handout #8. Java Generics

JAVA V Source files Java, winter semester

CSE 331. Generics (Parametric Polymorphism)

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

Exercise Session Week 6

The collections interfaces

Java Generics Java, summer semester

301AA - Advanced Programming [AP-2017]

Polymorphism (generics)

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

1.1. Annotations History Lesson - C/C++

Exercise 8 Parametric polymorphism November 17, 2017

301AA - Advanced Programming [AP-2017]

Java Design Goals. Lecture 32: Java. Java Original implementations slow! Exceptions & Subtyping. - void method readfiles() throws IOException {...}!

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

Java Generics -- an introduction. Based on

Section 10 MATERIAL PULLED FROM LAST SECTION AND LAST YEAR S SLIDES

#Students per correct answers

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

PARAMETRIC POLYMORPHISM

Stronger vs Weaker (one more time!) Requires more? Promises more? (stricter specifications on what the effects entail)

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

CSE 331 Software Design & Implementation

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

Subtyping for behaviour?

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Variance. Svetlana Isakova

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Software Engineering. Prof. Agostino Poggi

Introducing Generics

Outline. More optimizations for our interpreter. Types for objects

Collections, Maps and Generics

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Refactoring Java Generics by Inferring Wildcards, In Practice

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

C# Generics. Object Oriented Programming (236703) Winter

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Java Generics

Comp215: Thinking Generically

CSE331 Spring 2015, Final Examination June 8, 2015

Taming the Wildcards

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

Objects and Iterators

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007

Object typing and subtypes

Java: exceptions and genericity

CSE 331 Software Design & Implementation

Java Object Oriented Design. CSC207 Fall 2014

Java 1.5 in a Nutshell

Generics method and class definitions which involve type parameters.

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Compiler Construction 2009/2010 Polymorphic Types and Generics

The list abstract data type defined a number of operations that all list-like objects ought to implement:

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Compiler Construction 2016/2017 Polymorphic Types and Generics

Subtyping for behaviour?

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

COMP6700/2140 Generic Methods

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Properties of an identifier (and the object it represents) may be set at

Announcements. Written Assignment 2 Due Monday at 5:00PM. Midterm next Wednesday in class, 11:00 1:00. Midterm review session next Monday in class.

CSCE 314 Programming Languages. Type System

Java Generics. Lecture CS1122 Summer 2008

Exercise 13 Self-Study Exercise Sheet

Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

C# Adds Useful Features

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

6. Generic and Virtual Types

Subtyping for behaviour?

Topic 7: Algebraic Data Types

CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules:

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Lecture 4. Types, Memory, Exceptions

Chapter 10 Classes Continued. Fundamentals of Java

Java 5. Lecture 33: Java 5. Generics Finally Added. Constrained Genericity

Recursive Types and Subtyping

INSTRUCTIONS TO CANDIDATES

Transcription:

CSCE 314 Programming Languages! Java Generics II Dr. Hyunyoung Lee!!! 1

Type System and Variance Within the type system of a programming language, variance refers to how subtyping between complex types (e.g., list of Cats versus list of Animals, and function returning Cat versus function returning Animal) relates to subtyping between their components (e.g., Cats and Animals). 2

Covariance and Contravariance Within the type system of a programming language, a typing rule or a type constructor is: covariant if it preserves the ordering of types, which orders types from more specific to more generic contravariant if it reverses this ordering invariant if neither of these applies. 3

Co/Contravariance Idea Read-only data types can be covariant; Write-only data types can be contravariant; Mutable data types which support read and write operations should be invariant.! Even though Java arrays are a mutable data type, Java treats array types covariantly, by marking each array object with a type when it is created. 4

Covariant Method Return Type Return types of methods in Java can be covariant: class Animal {... public Animal clone() { return new Animal(); class Panda extends Animal {... public Panda clone() { return new Panda(); This is safe - whenever we call Animal s clone(), we get at least an Animal, but possibly something more (a subtype of Animal) Animal a = new Panda();... Animal b = a.clone(); // returns a Panda, OK 5

Covariant Method Argument Type (Bad Idea) Would this be a good idea? class Animal {... public bool compare(animal) {... class Panda extends Animal {... public bool compare(panda) {... Covariant argument types are not type safe, and thus not supported in (most) mainstream languages including Java Animal a = new Panda(); Animal b = new Animal();... a.compare(b); // type error at run time 6

Contravariant Argument Types? Contravariant argument types would be safe, but they have not been found useful and hence not supported in practical languages (not in C ++ nor in Java). class Animal {... public bool compare(panda) {... class Panda extends Animal {... public bool compare(animal) {... Summary: When overriding methods in Java - invariant argument type, covariant return type. Co- and contravariance of parameter and argument types are best captured with this subtyping rules between function types: U1 <: U2 T2 <: T1 U2 T2 <: U1 T1 7

Co- and Contravariance and Generic Types The same phenomenon occurs with generic definitions. Subtyping of generic types: Assume B<T> <: A<T> and Integer <: Number Which of these are true (safe)? B<Integer> <: A<Integer> B<Integer> <: B<Number> B<Integer> <: A<Number> Only the first (pointwise subtyping) Other two are forms of covariance, and unsafe(unless restricted suitably) 8

Co/Contravariance and Generic Types (Cont.) In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>. List<String> ls = new ArrayList<String>(); // ok List<Object> lo = ls; // not ok, consider the following lo.add(new Object()); // still ok String s = lo.get(0); //attempt to assign an Object to a String! 9

Co- and Contravariance Generic class C<T> is covariant with respect to T if A <: B implies C<A> <: C<B> Generic class C<T> is contravariant with respect to T if A <: B implies C<B> <: C<A> Generic class C<T> is invariant with respect to T if C<A> <: C<B> holds only if A = B. Generic class C<T> is bivariant with respect to T if C<A> <: C<B> for any A and B. 10

Example: Java Arrays Object[] o = new String[]{"1", "2", "3"; o[0] = new Integer(1); // throws here // OK First statement OK. Java arrays are (unsafely) covariant: String <: Object String[] <: Object[] You can think of String[] as Array<String> From the type checker s perspective, second OK Integer <: Object However, the second statement is an attempt to assign an Integer in place of String. Full functionality of arrays does not safely allow co/contravariance. Reasons: 1. Covariant arrays would be safe for reading elements from them. 2. Contravariant arrays would be safe for writing elements into them. 3. Java arrays support both reading and writing. 11

When is Co/Contravariance Safe? Covariance on type parameter T requires T not appear as a type of a writable field, or an argument type of a method. Contravariance on type parameter T requires T not appear as a type of a readable field, or as a return type of a method. Example: class below is safely contravariant on X, and covariant on Y class Pair<X, Y> { private X fst; private Y snd; Pair(X a, Y b) { this.fst = a; this.snd = b; void setfst(x a) { this.fst = a; Y getsnd() { return this.snd; 12

Using Co/Contravariant Pair Assume L <: D <: A, and assume co- and contravariant subtyping class Pair<X, Y> { private X fst; private Y snd; Pair(X a, Y b) { this.fst = a; this.snd = b; void setfst(x a) { this.fst = a; Y getsnd() { return this.snd; void getandset(pair<d, D> p, D d) { p.setfst(d); D x = p.getsnd(); getandset(new Pair<A, L>(), new D()); // This would be safe getandset(new Pair<L, A>(), new D()); // This would be unsafe // It would be safe to allow: Pair<A, L> <: Pair<D, D> 13 Example: Animal Dog extends Animal Labrador extends Dog! Labrador <: Dog <: Animal

Java s Approach for Safe Covariance Parametric polymorphisms and subtype polymorphism leaves a bit of a gap in between. Various co/contravariance solutions attempt to fill that gap. Java s approach is wildcards. Example: public abstract class Shape { public abstract void drawon (Canvas c); public class Circle extends Shape { private int x, y, radius; public void drawon (Canvas c) {... public class Line extends Shape { private int x1, y1, x2, y2; public void drawon (Canvas c) {... 14

Wildcards Bound From Above Example: List<Line> and List<Shape> public class Canvas { public void draw(list<shape> shapes) { for (Shape s: shapes) s.drawon(this); List<Line> ll;... ; canvas.draw(ll); // error // No w w ith w ildcards public class Canvas { public void draw(list<? extends Shape> shapes) { for (Shape s: shapes) s.drawon(this); List<Line> ll;... ; canvas.draw(ll); // OK //? reads unknown, corresponds to a fresh type variable // Shape is the upper bound of the wildcard 15

Wildcards Bound From Below Contravariance expressed with wildcards: <T> void copy(list<t> src, List<? super T> dest) List<Object> lo; List<String> ls; copy(ls, lo); // ok {... dest.add(src.get(i))... copy(lo, ls); // not ok! Two alternative formulations of copy: <T> void copy(list<? extends T> src, List<T> dest); <T, S extends T> void copy(list<s> src, List<T> dest); The fresh type variable model describes wildcards to some extent, but does not apply in all contexts. 16

Type Inference with Wildcards <T> T choose (T a, T b) {... Set<Integer> intset =... List<String> stringlist =... choose(intset, stringlist); Without wildcards, only valid typing for T in the call to choose is Object With wildcards, T can be typed as Collection<?> 17

Typing and Subtyping of Wildcards For any T, List<T> <: List<?>! Since element type is not known of an object of type List<?>, no objects can be written to it (nulls can) but Objects can be read from it 18

Wildcards in Variable Types Wildcards are allowed in other contexts than in just method parameter types: types of local variables, fields, arrays Example: Set<?> aset = new HashSet<String>(); 19

Wildcard Capture Rule The type bound to a wildcard cannot (in general) be recovered. Example: public static <T> void addtoset(set<t> s, T t) {...... Set<?> aset = new HashSet<String>(); addtoset(aset, string ); // error However wildcard capture allows this in some situations <T> public static Set<T> foo(set<t> s) {...... Set<?> aset = new HashSet<String>(); Set<?> s = foo(aset); // ok Lee CSCE 314 TAMU In Set<?>, the type parameter of Set is bound to some type, and as foo is well-typed for Set<U> for any U, the call is fine (and T captures the wildcard). The capturing is not visible outside of the method where it occurs Set<String> bset = foo(aset); // error 20

Type Erasure 1. Backwards compatibility was a hard constraint for design 2. Generic Java programs are compiled to class files that run on unchanged JVM. 3. Generic types are used during type checking, then erased according to a set of translation rules: a. Type parameters are replaced with their bounds b. Parametrized types throw away the parameters c. Casts inserted where necessary [Note: Compared to time prior generics, run-time casts still prevail (no improvement on performance) but they ll never throw an exception.] 21

Example of Erasure Generic code class A<T> { abstract T id(t x); class B extends A<Integer> { Integer id(integer x) { return x; Translated code A<T> -> A T -> Object (T had no bound, thus the bound is Object) Create a bridge method to fix type incompatibilities created in the translation. class A { abstract Object id(object x); class B extends A { Integer id(integer x) { return x; Object id(object x) { return id((integer)(x)); // bridge 22

Example of Erasure (Cont.) Uses of generics must be translated too: Integer foo(a<integer> a) { return a.id(1); translates to: Integer foo(a a) { return (Integer)a.id(1); 23

Implications Only one run-time representation for all instances of a generic class: List<String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getclass()); // true Some natural code is unnaturally rejected: class Foo<T> { public void bar(t x) { T t = new T(); if(x instanceof T) { // error // error public static void static_bar(t t) { // error public static List<T> l; // error Last two: no type parameters allowed in static context. 24

Implications (Cont.) Type erasure can lead to two methods having ambiguous signatures class C<T> { T id (T x) {... class D extends C<String> { Object id(object x) {... Illegal, C.id and D.id have the same type erasure. Two different bounds for the same parameter cannot have same erasures. A class may not directly or indirectly implement two interfaces with same erasures: Another example: class B implements I<Integer> { class C extends B implements I<String> { class DecimalString implements Comparable<Number>, Comparable<String> {... 25

Primitive Types boolean, int, etc. not allowed as type arguments for the type parameters. Fix: Autoboxing, auto-unboxing of primitive types: ArrayList<Integer> list = new ArrayList<Integer>(); // used to be like this list.add(0, new Integer(42)); int total = (list.get(0)).intvalue(); // thanks to auto(un)boxing, one can say list.add(0, 42); total = list.get(0); Still affects performance. 26

Type Erasure Summary Type erasure was chosen for it so that no changes are required to the instruction set of the JVM. Desire to retain backward compatibility affected design decisions in Java libraries as well. Some confusing issues - sometimes compromises are necessary in practical language design. Aside: C# generics very similar, but C# does not fully erase type information. 27