CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping. Dan Grossman Winter 2013

Similar documents
CSE341, Fall 2011, Lecture 26 Summary

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CS152: Programming Languages. Lecture 24 Bounded Polymorphism; Classless OOP. Dan Grossman Spring 2011

Last major topic: Subtyping. CSE341: Programming Languages Lecture 24 Subtyping. A tiny language. Records (half like ML, half like Java)

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018

CSE341, Spring 2013, Final Examination June 13, 2013

CSE341: Programming Languages Lecture 20 Arrays and Such, Blocks and Procs, Inheritance and Overriding. Dan Grossman Spring 2017

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CS-XXX: Graduate Programming Languages. Lecture 23 Types for OOP; Static Overloading and Multimethods. Dan Grossman 2012

Subtyping: broad definitions. Not Subtyping: type variable instantiation. Mutable Records (half like ML, half like Java/Scala)

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

Java Object Oriented Design. CSC207 Fall 2014

Don t Believe the Hype. CS152: Programming Languages. Lecture 21 Object-Oriented Programming. Class-based OOP. So what is OOP?

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

Late Binding; OOP as a Racket Pattern

Chapter 5 Object-Oriented Programming

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

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

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

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

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

Quiz. Programming Languages. CSE 130 : Fall Lecture 16: Static Types for Objects. Ranjit Jhala UC San Diego

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

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CS558 Programming Languages

Goal. CS152: Programming Languages. Lecture 15 Parametric Polymorphism. What the Library Likes. What The Client Likes. Start simpler.

ob-ject: to feel distaste for something Webster's Dictionary

Featherweight Java (FJ)

CSE341 Autumn 2017, Final Examination December 12, 2017

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

CSCI-GA Scripting Languages

Chapter 14 Abstract Classes and Interfaces

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

CS-XXX: Graduate Programming Languages. Lecture 22 Class-Based Object-Oriented Programming. Dan Grossman 2012

Recursive Types and Subtyping

Records. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

Programming Languages Lecture 15: Recursive Types & Subtyping

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

CSCI-GA Final Exam

Tradeoffs. CSE 505: Programming Languages. Lecture 15 Subtyping. Where shall we add useful completeness? Where shall we add completeness?

CSE341 Spring 2017, Final Examination June 8, 2017

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

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

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

CSE 341: Programming Languages

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Data Structures (list, dictionary, tuples, sets, strings)

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

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

Lecture 13: Subtyping

CSE341 Spring 2017, Final Examination June 8, 2017

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

JAVA MOCK TEST JAVA MOCK TEST II

Subtyping and Objects

Java Fundamentals (II)

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

CS 360: Programming Languages Lecture 12: More Haskell

G Programming Languages - Fall 2012

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INSTRUCTIONS TO CANDIDATES

COURSE 2 DESIGN PATTERNS

Variables and Bindings

Object typing and subtypes

ITI Introduction to Computing II

Advanced oo concepts Specialization of behaviour? Multiple inheritance - alternatives to. Inner classes Classes

CSE 505, Fall 2007, Final Examination 10 December Please do not turn the page until everyone is ready.

Harvard School of Engineering and Applied Sciences Computer Science 152

Object Oriented Issues in VDM++

- couldn t be instantiated dynamically! - no type or other method of organizing, despite similarity to

Polymorphism and Interfaces. CGS 3416 Spring 2018

CSE3322 Programming Languages and Implementation

CS-202 Introduction to Object Oriented Programming

Inheritance and object compatibility

ITI Introduction to Computing II

CS 11 java track: lecture 3

Semantic Analysis and Type Checking

Types and Classes. I II From predefined (simple) and user-defined (composite) types via Abstract data types

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Object-oriented aspects of MOBY

Typical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated

Semantic Analysis. Lecture 9. February 7, 2018

Inheritance and Substitution (Budd chapter 8, 10)

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Transcription:

CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping Dan Grossman Winter 2013

Now Use what we learned about subtyping for records and functions to understand subtyping for class-based OOP Like in Java/C# Recall: Class names are also types Subclasses are also subtypes Substitution principle: Instance of subclass should usable in place of instance of superclass 2

An object is Objects: mostly records holding fields and methods Fields are mutable Methods are immutable functions that also have access to self So could design a type system using types very much like record types Subtypes could have extra fields and methods Overriding methods could have contravariant arguments and covariant results compared to method overridden Sound only because method slots are immutable! 3

Actual Java/C# Compare/contrast to what our theory allows: 1. Types are class names and subtyping are explicit subclasses 2. A subclass can add fields and methods 3. A subclass can override a method with a covariant return type (No contravariant arguments; instead makes it a nonoverriding method of the same name) (1) Is a subset of what is sound (so also sound) (3) Is a subset of what is sound and a different choice (adding method instead of overriding) 4

Classes vs. Types A class defines an object's behavior Subclassing inherits behavior and changes it via extension and overriding A type describes an object's methods argument/result types A subtype is substitutable in terms of its field/method types These are separate concepts: try to use the terms correctly Java/C# confuse them by requiring subclasses to be subtypes A class name is both a class and a type Confusion is convenient in practice 5

Optional: More details Java and C# are sound: They do not allow subtypes to do things that would lead to method missing or accessing a field at the wrong type Confusing (?) Java example: Subclass can declare field name already declared by superclass Two classes can use any two types for the field name Instance of subclass have two fields with same name Which field is in scope depends on which class defined the method 6

self/this is special Recall our Racket encoding of OOP-style Objects have a list of fields and a list of functions that take self as an explicit extra argument So if self/this is a function argument, is it contravariant? No, it is covariant: a method in a subclass can use fields and methods only available in the subclass: essential for OOP class A { int m(){ return 0; } } class B extends A { int x; int m(){ return x; } } Sound because calls always use the whole object for self This is why coding up your own objects manually works much less well in a statically typed languages 7

What are generics good for? Some good uses for parametric polymorphism: Types for functions that combine other functions: fun compose (g,h) = fn x => g (h x) (* compose : ('b -> 'c) * ('a -> 'b) -> ('a -> 'c) *) Types for functions that operate over generic collections val length : 'a list -> int val map : ('a -> 'b) -> 'a list -> 'b list val swap : ('a * 'b) -> ('b * 'a) Many other idioms General point: When types can be anything but multiple things need to be the same type 8

Generics in Java Java generics a bit clumsier syntactically and semantically, but can express the same ideas Without closures, often need to use (one-method) objects See also earlier optional lecture on closures in Java/C Simple example without higher-order functions (optional): class Pair<T1,T2> { T1 x; T2 y; Pair(T1 _x, T2 _y){ x = _x; y = _y; } Pair<T2,T1> swap() { return new Pair<T2,T1>(y,x); } } 9

Subtyping is not good for this Using subtyping for containers is much more painful for clients Have to downcast items retrieved from containers Downcasting has run-time cost Downcasting can fail: no static check that container holds the type of data you expect (Only gets more painful with higher-order functions like map) class LamePair { Object x; Object y; LamePair(Object _x, Object _y){ x=_x; y=_y; } LamePair swap() { return new LamePair(y,x); } } // error caught only at run-time: String s = (String)(new LamePair("hi",4).y); 10

What is subtyping good for? Some good uses for subtype polymorphism: Code that needs a Foo but fine to have more than a Foo Geometry on points works fine for colored points GUI widgets specialize the basic idea of being on the screen and responding to user actions 11

Awkward in ML ML does not have subtyping, so this simply does not type-check: (* {x:real, y:real} -> real *) fun disttoorigin ({x=x,y=y}) = Math.sqrt(x*x + y*y) val five = disttoorigin {x=3.0,y=4.0,color="red"} Cumbersome workaround: have caller pass in getter functions: (* ('a -> real) * ('a -> real) * 'a -> real *) fun disttoorigin (getx, gety, v) = Math.sqrt((getx v)*(getx v) + (gety v)*(gety v)) And clients still need different getters for points, color-points 12

Wanting both Could a language have generics and subtyping? Sure! More interestingly, want to combine them Any type T1 that is a subtype of T2 Called bounded polymorphism Lets you do things naturally you cannot do with generics or subtyping separately 13

Example Method that takes a list of points and a circle (center point, radius) Return new list of points in argument list that lie within circle Basic method signature: List<Point> incircle(list<point> pts, Point center, double r) { } Java implementation straightforward assuming Point has a distance method: List<Point> result = new ArrayList<Point>(); for(point pt : pts) if(pt.distance(center) < r) result.add(pt); return result; 14

Subtyping? List<Point> incircle(list<point> pts, Point center, double r) { } Would like to use incircle by passing a List<ColorPoint> and getting back a List<ColorPoint> Java rightly disallows this: While incircle would do nothing wrong its type does not prevent: Returning a list that has a non-color-point in it Modifying pts by adding non-color-points to it 15

Generics? List<Point> incircle(list<point> pts, Point center, double r) { } We could change the method to be <T> List<T> incircle(list<t> pts, Point center, double r) { } Now the type system allows passing in a List<Point> to get a List<Point> returned or a List<ColorPoint> to get a List<ColorPoint> returned But cannot implement incircle properly: method body should have no knowledge of type T 16

Bounds What we want: <T> List<T> incircle(list<t> pts, Point center, double r) where T <: Point { } Caller uses it generically, but must instantiate T with some subtype of Point (including Point) Callee can assume T <: Point so it can do its job Callee must return a List<T> so output will contain only elements from pts 17

Real Java The actual Java syntax: <T extends Pt> List<T> incircle(list<t> pts, Pt center, double r) { List<T> result = new ArrayList<T>(); for(t pt : pts) if(pt.distance(center) < r) result.add(pt); return result; } Note: For backward-compatibility and implementation reasons, in Java there is actually always a way to use casts to get around the static checking with generics With or without bounded polymorphism 18