Generics with Type Bounds

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

Parametric polymorphism and Generics

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Advanced Programming Generics Collections

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

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

Generalized Code. Fall 2011 (Honors) 2

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Java 5 New Language Features

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

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

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

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Advances in Programming Languages: Type accuracy

PARAMETRIC POLYMORPHISM

CMSC 202. Generics II

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

301AA - Advanced Programming [AP-2017]

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

Rules and syntax for inheritance. The boring stuff

Operational Semantics. One-Slide Summary. Lecture Outline

INSTRUCTIONS TO CANDIDATES

301AA - Advanced Programming [AP-2017]

A Short Summary of Javali

Operational Semantics of Cool

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

University of Palestine. Mid Exam Total Grade: 100

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Lecture Set 4: More About Methods and More About Operators

(Not Quite) Minijava

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

CS111: PROGRAMMING LANGUAGE II

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Java Fundamentals (II)

Lecture Set 4: More About Methods and More About Operators

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Computer Science II (20082) Week 1: Review and Inheritance

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Definition of DJ (Diminished Java)

Generics method and class definitions which involve type parameters.

COMP6700/2140 Generic Methods

generic programming alberto ferrari university of parma

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

Lecture 5: Methods CS2301

Lecture 4. Types, Memory, Exceptions

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Primitive Java Generic Class

Reflection. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 28

Exercise 12 Initialization December 15, 2017

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

IC Language Specification

Programming Languages and Techniques (CIS120)

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Outline. More optimizations for our interpreter. Types for objects

Exercise 12 Initialization December 16, 2016

Programming Languages and Techniques (CIS120)

Collections Algorithms

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

CMSC 132: Object-Oriented Programming II

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far.

CS-201 Introduction to Programming with Java

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and

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

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism

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.

Examination Questions Midterm 1

Exam 2. Topics. Preconditions vs. Exceptions. Exam 2 Review. Exam 2 on Thursday, March 29 th. Closed book, closed computer, closed phone

INHERITANCE. Spring 2019

Java: introduction to object-oriented features

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Lecture #23: Conversion and Type Inference

C11: Garbage Collection and Constructors

Lecture Outline. Type systems and their expressiveness. Type Checking in COOL (II) Type checking with SELF_TYPE in COOL

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

CSCE 314 Programming Languages

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Introduction to Programming Using Java (98-388)

Programming Languages and Techniques (CIS120)

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CMSC330 Fall 2013 Practice Problems 6 Solutions

Programming Language Concepts: Lecture 2

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

Singleton. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 29

The Singleton Pattern. Design Patterns In Java Bob Tarr

Transcription:

Generics with Type Bounds Computer Science and Engineering College of Engineering The Ohio State University Lecture 27

Generic Methods Like classes, methods can be generic class ArrayOps { //ordinary nongeneric class static <T> T midpoint(t[] A); <T> int nonnulllength(t[] A); Scope of type parameter limited to method Instantiation with a specific parameter type not needed when invoking method Parameter type is inferred from arguments String s = ArrayOps.midpoint(args); Date d = ArrayOps.midpoint(timeline); int c = arrayworker.nonnulllength(args); (Can also use return type, when assigned) But explicit type invocation is legal too i = MathUtilities.<Integer>max(42, 34);

Example: Generic Methods class ArrayOps { public static <T> T midpoint(t[] A) { assert A.length >= 1; return A[A.length/2]; public <T> int nonnulllength(t[] A) { int count = 0; for (T t : A) if (t!= null) count++; return count; public static void main(string[] args) { ArrayOps arrayworker = new ArrayOps(); String s1 = ArrayOps.midpoint(args); String s2 = ArrayOps.<String>midpoint(args); int x = arrayworker.nonnulllength(args); int y = arrayworker.<string>nonnulllength(args);

Type Bounds Ordinary parameters have 2 parts: name and type void somemethod(person p) Inside method, know p refers to a Person (or below) SSN id = p.getssn(); //ok, p is Person (or Student) Generics have only 1 part: a name, like T Inside method, know only that T is Object (or below) <T> void genericmethod(t t) { t.hashcode(); //ok, all Objects have hashcode So generic code must be applicable to all objects? What if we want to restrict type arguments? <T> void genericmethod(t t) { SSN id = t.getssn(); //error: no getssn for Object Solution: Bound type argument above by Person <T extends Person> void genericmethod(t t) { SSN id = t.getssn();

Example: Type Bounds class Filter { static <T> T max(t t1, T t2) { return (t1.compareto(t2) <= 0? t2 : t1); BigNatural nat1 =... BigNatural nat2 =... System.out.println(Filter.max(nat1, nat2));

Question: Why not This Way? class Filter { static <T> Comparable<T> max(comparable<t> t1, Comparable<T> t2) { return (t1.compareto(t2) <= 0? t2 : t1); BigNatural nat1 =... BigNatural nat2 =... System.out.println(Filter.max(nat1, nat2));

Example: Type Bounds class Filter { static <T extends Comparable<T>> T max(t t1, T t2) { return (t1.compareto(t2) <= 0? t2 : t1); BigNatural nat1 =... BigNatural nat2 =... System.out.println(Filter.max(nat1, nat2));

Arrays and Inheritance Consider 3 types: Student, Person, Object Student extends Person, Person extends Object Subtyping: a Student is a Person A Student can do everything a Person can do Client would rather have Student to use Implementer would rather write Person Code expecting a Person, can be given a Student boolean older (int age, Person p); Question: a Student[] is a Person[]? Can a Student[] do everything a Person[] can do? Can code expecting a Person[] be given a Student[] instead? boolean allolder(int age, Person[] ps);

Arrays and Co/Contra-Variance Object Object[] Student[] Person Person[] or? Person[] Student Student[] Object[] Covariance Contravariance

Strawman 1: Covariance Student[] is a Person[], Person[] is an Object[] boolean allolder (int age, Person[] ps) { boolean result = true; for (Person p : ps) if (p.getage() < age) result = false; return result; //ok for arrays of Students too Counter-example void clobberfirst (Person[] ps) { ps[0] = new Infant( Baby Doe ); //ok since Infant extends Person Student[] roster =... //assert: roster contains only Students clobberfirst(roster); //trouble: Dynamic type of roster[0] is Infant roster[0].grantdegree();

Strawman 2: Contravariance Object[] is a Person[], Person[] is a Student[] void populateclass(student[] roster) { for (int i=0; i<roster.length; i++) roster[i] = new Student(); //ok for an array of Persons too void formjury(person[] panel) { populateclass(panel); Counter-example void graduate (Student[] roster) { for (Student s : roster) //trouble: dynamic type of s is Person s.grantdegree(); Person[] ps =... graduate(ps);

Java s Choice Neither is right! A Student[] can not do everything a Person[] can do! e.g. it can not contain an Infant A Person[] can not do everything a Student[] can do! e.g. it can not calculate a max GPA Java s choice: Covariance Student[] is a Person[]! Consequence: We live dangerously If the wrong type of object is assigned to an array element, ArrayStoreException is thrown

Generics and Wildcards Wildcard?: Refers to stack of any kind Stack<?> Example boolean largesize(int limit, Stack<?> s) { if (s.size() > limit) return true; else return false; Subtyping: Every Stack is a Stack<?> Stack<String> args =... Stack<People> crew =... flag = largesize(3, args); //ok flag = largesize(32, crew); //ok

Generics and Inheritance Is a Stack<Student> a Stack<Person>? Can a Stack<Student> do everything a Stack<Person> can do? Can code expecting a Stack<Person> be given a Stack<Student> instead? Java s choice: No! For a generic class G, there is no implicit subtyping relationship between G<A> and G<B> Neither covariance nor contravariance Regardless of any subtyping relationship between A and B

Generics: Co/Contra-variance Similar to arrays Sometimes covariance is ok Sometimes contravariance is ok Consider code written for Stack<Person> boolean somemethod(stack<person> s); Questions: Can a Stack<Student> be passed in instead? Can a Stack<Object> be passed in instead? Answer: It depends on what client code does with s! Some code works fine for Stack<Student> Some code works fine for Stack<Object>

Both Forms Example 1: Getting from stack int firstage(stack<person> s) { Person p = s.pop(); return p.getage(); Works when argument is a Stack<Student> Does not work when given a Stack<Object> Example 2: Putting into stack void addchild(stack<person> s) { s.push(new Person(3)); Works when argument is a Stack<Object> Does not work when given a Stack<Student>

Upper Type Bounds: Covariance Combine wildcard with type bound Stack<? extends Person> Person is an upper bound on type parameter Reflects covariant relationship int firstage(stack<? extends Person> s) { Person p = s.pop(); return p.getage(); List<? extends Number> figures = new ArrayList<Number>(); figures = new ArrayList<Integer>(); Use when code gets from generic

Lower Type Bounds: Contravariance Combine wildcard with type bound Stack<? super Person> Person is a lower bound on type parameter Reflects contravariant relationship void addchild(stack<? super Person> s) { s.push(new Person(3)); List<? super Integer> figures = new ArrayList<Integer>(); figures = new ArrayList<Number>(); Use when client code puts to generic

Summary Generic methods Type parameter applied to individual methods Inheritance and arrays Java arrays are covariant in their base type This is not type safe (wrong stores cause exception) Inheritance and generics: type bounds Use upper type bound when getting Use lower type bound when putting Use exact type when doing both