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

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

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

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

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

CS-XXX: Graduate Programming Languages. Lecture 9 Simply Typed Lambda Calculus. Dan Grossman 2012

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

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

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

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

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

CSE341, Fall 2011, Lecture 26 Summary

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

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CS558 Programming Languages

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

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

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

Subtyping. Lecture 13 CS 565 3/27/06

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Object Oriented Issues in VDM++

CS558 Programming Languages Winter 2013 Lecture 8

Inheritance and Polymorphism in Java

CSE 505: Concepts of Programming Languages

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

Concepts of Programming Languages

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Featherweight Java (FJ)

Subtyping (Dynamic Polymorphism)

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

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Programming II (CS300)

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

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

Rules and syntax for inheritance. The boring stuff

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type Checking in COOL (II) Lecture 10

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

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

Late Binding; OOP as a Racket Pattern

Classes Classes 2 / 36

CS558 Programming Languages

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

Object Oriented Paradigm

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

CS 251 Intermediate Programming Inheritance

Lecture #23: Conversion and Type Inference

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

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

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

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

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object

OVERRIDING. 7/11/2015 Budditha Hettige 82

CS558 Programming Languages

History C++ Design Goals. How successful? Significant constraints. Overview of C++

Classes, interfaces, & documentation. Review of basic building blocks

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CS558 Programming Languages

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

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

Lecture 16: Case Study: The Java Collections API

Programming Languages Lecture 15: Recursive Types & Subtyping

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

Example: Count of Points

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

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

Classes Classes 2 / 35

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

CS153: Compilers Lecture 11: Compiling Objects

VIRTUAL FUNCTIONS Chapter 10

Introduction to Object-Oriented Programming

Higher-Order Intensional Type Analysis. Stephanie Weirich Cornell University

Lab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018

CSE 431S Type Checking. Washington University Spring 2013

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

Interfaces, Mixins, & Multiple Inheritance

301AA - Advanced Programming [AP-2017]

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS105 C++ Lecture 7. More on Classes, Inheritance

Java Fundamentals (II)

Lecture 13: Subtyping

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

CS-202 Introduction to Object Oriented Programming

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

Lecture Notes on Programming Languages

PROGRAMMING LANGUAGE 2

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Object-Oriented Concepts and Design Principles

Introduction to Object-Oriented Programming

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

C++ Programming: Polymorphism

Inheritance and object compatibility

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

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

Inheritance and Polymorphism. CS180 Fall 2007

Transcription:

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

Revenge of Type Variables Sorted lists in ML (partial): type a slist make : ( a -> a -> int) -> a slist cons : a slist -> a -> a slist find : a slist -> a -> a option Getting by with OO subtyping: interface Cmp { Int f(object,object); } class SList {... some field definitions... constructor (Cmp x) {...} Slist cons(object x) {...} Object find(object x) {...} } Dan Grossman CS152 Spring 2011, Lecture 24 2

Wanting Type Variables Will downcast (potential run-time exception) the arguments to f and the result of find We are not enforcing list-element type-equality OO-style subtyping is no replacement for parametric polymorphism; we can have both: interface Cmp< a> { Int f( a, a); } // Cmp not a type class SList< a> { // SList not a type (SList<Int> e.g. is)... some field definitions (can use type a)... } constructor (Cmp< a> x) {...} Slist< a> cons( a x) {...} a find( a) {...} Dan Grossman CS152 Spring 2011, Lecture 24 3

Same Old Story Interface and class declarations are parameterized; they produce types The constructor is polymorphic For all T, given a Cmp<T>, it makes a SList<T> If o has type SList<T>, its cons method: Takes a T Returns a SList<T> No more downcasts; the best of both worlds Dan Grossman CS152 Spring 2011, Lecture 24 4

Complications Interesting interaction with overloading and multimethods class B { unit f(c<int> x) {...} unit f(c<string> x) {...} } class C< a> { unit g(b x) { x.f(self); } } For C<T> where T is neither Int nor String, can have no match Cannot resolve static overloading at compile-time without code duplication and no abstraction (C++) To resolve overloading or multimethods at run-time, need run-time type information including the instantiation T (C#) Could disallow such overloading (Java) Or could just reject this sort of call as unresolvable (?) Dan Grossman CS152 Spring 2011, Lecture 24 5

Wanting bounds There are compelling reasons to bound the instantiation of type variables Simple example: Use at supertype without losing that it s a subtype interface I { unit print(); } class Logger< a <: I > { // must apply to subtype of I a item; a get_it() { syslog(item.print()); item } } Without polymorphism or downcasting, client could only use get_it result for printing Without bound or downcasting, Logger could not print Issue isn t special to OOP Dan Grossman CS152 Spring 2011, Lecture 24 6

Fancy Example from A Theory of Objects Abadi/Cardelli With forethought and structural (non-named) subtyping, bounds can avoid some subtyping limitations interface Omnivore { unit eat(food); } interface Herbivore { unit eat(veg); } // Veg <= Food Allowing Herbivore Omnivore could make a vegetarian eat meat (unsound)! But this works: interface Omnivore< a <: Food > { unit eat( a); } interface Herbivore< a <: Veg > { unit eat( a); } If Herbivore<T> is legal, then Omnivore<T> is legal and Herbivore<T> <: Omnivore<T>! Useful for unit feed( a food, Omnivore< a> animal) {...} Dan Grossman CS152 Spring 2011, Lecture 24 7

Bounded Polymorphism This bounded polymorphism is useful in any language with universal types and subtyping. Instead of α.τ and Λα.e, we have α < τ.τ and Λα < τ.e: Change to be a list of bounds (α < τ ) instead of a set of type variables In e you can subsume from α to τ e 1 [τ 1 ] typechecks when τ 1 satisfies the bound in type of e 1 One limitation: When is ( α 1 <τ 1.τ 2 ) ( α 2 <τ 3.τ 4 )? Contravariant bounds and covariant bodies assuming bound are sound, but makes subtyping undecidable Requiring invariant bounds and covariant bodies regains decidability, but obviously allows less subtyping Dan Grossman CS152 Spring 2011, Lecture 24 8

Classless OOP OOP gave us code-reuse via inheritance and extensibility via late-binding Can we throw out classes and still get OOP? Yes Can it have a type system that prevents no match found and no best match errors? Yes, but we won t get there This is mind-opening stuff if you ve never seen it Will make up syntax as we go... Dan Grossman CS152 Spring 2011, Lecture 24 9

Make objects directly Everything is an object. You can make objects directly: let p = [ field x = 7; field y = 9; right_quad(){ x.gt(0) && y.gt(0) } // cf. 0.lte(y) ] p now bound to an object Can invoke its methods and read/write its fields No classes: Constructors are easy to encode let make_pt = [ doit(x0,y0) { [ field x=x0; field y=y0;... ] } ] Dan Grossman CS152 Spring 2011, Lecture 24 10

Inheritance and Override Building objects from scratch won t get us late-binding and code reuse. Here s the trick: clone method produces a (shallow) copy of an object method slots can be mutable let o1 = [ // still have late-binding odd(x) {if x.eq(0) then false else self.even(x-1)} even(x) {if x.eq(0) then true else self.odd(x-1) } ] let o2 = o1.clone() o2.even(x) := {(x.mod(2)).eq(0)} Language doesn t grow: just methods and mutable slots Can use for constructors too: clone and assign fields Dan Grossman CS152 Spring 2011, Lecture 24 11

Extension But that trick doesn t work to add slots to an object, a common use of subclassing Having something like extend e1 (x=e2) that mutates e1 to have a new slot is problematic semantically (what if e1 has a slot named x) and for efficiency (may not be room where e1 is allocated) Instead, we can build a new object with a special parent slot: [parent=e1; x=e2] parent is very special because definition of method-lookup (the issue in OO) depends on it (else this isn t inheritance) Dan Grossman CS152 Spring 2011, Lecture 24 12

Method Lookup To find the m method of o: Look for a slot named m If not found, look in object held in parent slot But we still have late-binding: for method in parent slot, we still have self refer to the original o. Two inequivalent ways to define parent=e1: Delegation: parent refers to result of e1 Embedding: parent refers to result of e1.clone() Mutation of result of e1 (or its parent or grandparent or...) exposes the difference We ll assume delegation Dan Grossman CS152 Spring 2011, Lecture 24 13

Oh so flexible Delegation is way more flexible (and simple!) (and dangerous!) than class-based OO: The object being delegated to is usually used like a class, but its slots may be mutable Assigning to a slot in a delegated object changes every object that delegates to it (transitively) Clever change-propagation but as dangerous as globals and arguably more subtle? Assigning to a parent slot is dynamic inheritance changes where slots are inherited from Classes restrict what you can do and how you think, e.g., never thinking of clever run-time modifications of inheritance Dan Grossman CS152 Spring 2011, Lecture 24 14

Javascript: A Few Notes Javascript gives assignment extension semantics if field not already there. Implementations use indirection (hashtables). parent is called prototype new F(...) creates a new object o, calls F with this bound to o, and returns o. No special notion of constructor Functions are objects too This isn t quite prototype-based inheritance, but can code it up: function inheritfrom(o) { function F() {} F.prototype = o; return new F(); } No clone (depending on version), but can copy fields explicitly Dan Grossman CS152 Spring 2011, Lecture 24 15

Rarely what you want We have the essence of OOP in a tiny language with more flexibility than we usually want Avoid it via careful coding idioms: Create trait/abstract objects: Just immutable methods Analogous role to virtual-method tables Extend with prototype/template objects: Add mutable fields but don t mutate them Analogous role to classes Clone prototypes to create concrete/normal objects Analogous role to objects (clone is constructor) Traits can extend other traits and prototypes other prototypes Analogous to subclassing Dan Grossman CS152 Spring 2011, Lecture 24 16

Coming full circle This idiom is so important, it s worth having a type system that enforces it For example, a template object cannot have its members accessed (except clone) We end up getting close to classes, but from first principles and still allowing the full flexibility when you want it Dan Grossman CS152 Spring 2011, Lecture 24 17