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

Similar documents
CMSC 330: Organization of Programming Languages. Polymorphism

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

CMSC 330: Organization of Programming Languages. Review Choices

Review Choices. CMSC 330: Organization of Programming Languages. Environments and Closures. Example. Curried Functions in OCaml (cont d)

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

Rules and syntax for inheritance. The boring stuff

CMSC330 Fall 2013 Practice Problems 6 Solutions

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

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

1.1. Annotations History Lesson - C/C++

CMSC330. Objects, Functional Programming, and lambda calculus

OCaml Language Choices CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages

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

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Generic programming in OO Languages

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

CS-202 Introduction to Object Oriented Programming

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Conformance. Object-Oriented Programming Spring 2015

CS558 Programming Languages

Concepts of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Operators and Expressions

First IS-A Relationship: Inheritance

Introduction to Programming Using Java (98-388)

More Relationships Between Classes

Announcements. Java Graphics. Exceptions. Java Odds & Ends

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

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS558 Programming Languages

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

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

1 Shyam sir JAVA Notes

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Introduction to Object-Oriented Programming

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

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

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Object-oriented Programming. Object-oriented Programming

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Inheritance and Polymorphism

Computer Science 1 Ah

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Project 2 Due 11:59:59pm Wed, Mar 7, 2012

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

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

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

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

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

CMSC 341. Nilanjan Banerjee

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

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

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

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Exercise 8 Parametric polymorphism November 18, 2016

Generalized Code. Fall 2011 (Honors) 2

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

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

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

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

CSCE 314 Programming Languages

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

Generics with Type Bounds

COMP1008 Exceptions. Runtime Error

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

(Not Quite) Minijava

Programming Languages and Techniques (CIS120)

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

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

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

Binghamton University. CS-140 Fall Dynamic Types

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

The collections interfaces

Programming Languages and Techniques (CIS120)

CLASS DESIGN. Objectives MODULE 4

Primitive Java Generic Class

Parametric polymorphism and Generics

Object Oriented Programming: Based on slides from Skrien Chapter 2

Programming Languages 2nd edition Tucker and Noonan"

Generics in Java and Beyond

Weeks 6&7: Procedures and Parameter Passing

Example: Count of Points

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

CS 231 Data Structures and Algorithms, Fall 2016

Photo credit: Andrew Kennedy JAVA GENERICS

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

Strict Inheritance. Object-Oriented Programming Winter

Array. Prepared By - Rifat Shahriyar

Object-oriented programming in...

Harvard School of Engineering and Applied Sciences Computer Science 152

Transcription:

CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø Same function applied to different data types Ø Example Data types let id = function x -> x Ø Same data type can contain different data types Ø Example type a option = None Some of a CMSC 330 2 Two Kinds of Polymorphism Described by Strachey in 1967 Ad hoc and Subtype polymorphism Range of types is finite Combinations must be specified in advance Behavior may differ based on type of arguments Parametric polymorphism Code written without mention of specific type May be transparently used with arbitrary # of types Behavior is same for different types of arguments Polymorphism Overview Subtype (for OO languages) Sometimes considered ad-hoc Ad-hoc Overloading Ø Operator overloading Ø Method name overloading Parametric ML types A.k.a. generic programming (for OO languages) Ø Bounded parametric polymorphism combines subtype and parametric polymorphism CMSC 330 3 CMSC 330 4 1

Subtype Polymorphism Any context expecting an object of type A can be given an object of type B where B is a subtype of A Example: Function parameter has type A So it may be called with arguments of type B Subtyping enabled by inheritance class A { class B extends A { // subclass static void f(a arg) { A a = new A(); B b = new B(); f(a); f(b); // f accepts arg of type A or B Subtype Polymorphism More generally, B is a subtype of A if it can do everything A can Has the same fields, methods Java interfaces also support subtyping interface A { class B implements A { class C implements A { static void f(a arg) { B b = new B(); C c = new C(); f(b); f(c); // f accepts arg of type B or C CMSC 330 5 CMSC 330 6 When can we extend or implement? When can A extend B? Complicated! Roughly: When it overrides methods such that the overriding types are subtypes of original When can A implement B? When it has methods whose types are the same as those required by the interface Overloading Multiple copies of function Same function name But different number / type of parameters Arguments determine function actually invoked Function is uniquely identified not by function name, but by name + order & number of argument type(s) Ø print(integer i) print_integer( ) Ø print(float f) print_float( ) static void print(integer arg) { static void print(float arg) { print(1); // invokes 1 st print print(3.14); // invokes 2 nd print CMSC 330 7 CMSC 330 8 2

Overloading and Overriding Interaction is confusing Common mistake is inadvertently overload when you mean to override public class Point { private int x = 0, y = 0; public boolean equals(point p) { //overloads return (p.x == x) && (p.y == y); public static void main(string args[]) { Point p1 = new Point(); Point p2 = new Point(); Object o = p1; System.out.println(o.equals(p2)); //prints false System.out.println(p1.equals(p2)); //prints true Operator Overloading Treat operators as functions With special syntax for invocations Behavior different depending on operand type Example + in Java 1 + 2 // integer addition 1.0 + 3.14 // float addition Hello + world // string concatenation CMSC 330 9 CMSC 330 10 Operator Overloading (cont.) User-specified operator overloading Supported in languages such as Ruby, C++ Makes user data types appear more like native types Examples Defining function for ^ operator class MyS def ^ (arg)... end end Ruby class MyS { MyS operator^(mys arg){... C++ Parametric Polymorphism Found in statically typed functional languages OCaml, ML, Haskell Example let hd = function (h::_) -> h a list -> a Also used in object oriented programming Known as generic programming Example: Java, C++ CMSC 330 11 CMSC 330 12 3

An Integer Stack Implementation class Stack { class Entry { Integer elt; Entry next; Entry(Integer i, Entry n) { elt = i; next = n; Entry thestack; void push(integer i) { thestack = new Entry(i, thestack); Integer pop() throws EmptyStackException { if (thestack == null) throw new EmptyStackException(); else { Integer i = thestack.elt; thestack = thestack.next; return i; Integer Stack Client Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop(); If we also want a stack of Floats, do we need to write a Float Stack class? CMSC 330 13 CMSC 330 14 An Object Stack Implementation class Stack { class Entry { Object elt; Entry next; Entry(Object i, Entry n) { elt = i; next = n; Entry thestack; void push(object i) { thestack = new Entry(i, thestack); Object pop() throws EmptyStackException { if (thestack == null) throw new EmptyStackException(); else { Object i = thestack.elt; thestack = thestack.next; return i; New Stack Client Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = (Integer) is.pop(); Object stacks are polymorphic & reusable push() works the same But now pop() returns an Object Ø Have to downcast back to Integer Not checked until run-time CMSC 330 15 CMSC 330 16 4

General Problem When we move from an X container to an Object container Methods that take X s as input parameters are OK Ø If you re allowed to pass Object in, you can pass any X in Methods that return X s as results require downcasts Ø You only get Objects out, which you need to cast down to X General characteristic of subtype polymorphism Parametric Polymorphism (for Classes) Java 1.5 introduced generics We can parameterize the Stack class by its element type Syntax Class declaration: class A<T> {... Ø A is the class name, as before Ø T is a type variable, can be used in body of class (...) Client usage declaration: A<Integer> x; Ø We instantiate A with the Integer type CMSC 330 17 CMSC 330 18 Parametric Polymorphism for Stack class Stack<ElementType> { class Entry { ElementType elt; Entry next; Entry(ElementType i, Entry n) { elt = i; next = n; Entry thestack; void push(elementtype i) { thestack = new Entry(i, thestack); ElementType pop() throws EmptyStackException { if (thestack == null) throw new EmptyStackException(); else { ElementType i = thestack.elt; thestack = thestack.next; return i; Stack<Element> Client Stack<Integer> is = new Stack<Integer>(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop(); No downcasts Type-checked at compile time No need to duplicate Stack code for every usage line i = is.pop(); can stay the same even if the type of is isn t an integer in every path through the program CMSC 330 19 CMSC 330 20 5

Parametric Polymorphism for Methods String is a subtype of Object 1. static Object id(object x) { return x; 2. static Object id(string x) { return x; 3. static String id(object x) { return x; 4. static String id(string x) { return x; Can t pass an Object to 2 or 4 3 doesn t type check Can pass a String to 1 but you get an Object back CMSC 330 21 Parametric Polymorphism, Again But id() doesn t care about the type of x It works for any type So parameterize the static method static <T> T id(t x) { return x; Integer i = id(new Integer(3)); Notice no need to instantiate id; compiler figures out the correct type at usage The formal parameter has type T, the actual parameter has type Integer CMSC 330 22 Standard Library, and Java 1.5 (and later) Part of Java 1.5 (called generics ) Comes with replacement for java.util.* Ø class LinkedList<A> {... Ø class HashMap<A, B> {... Ø interface Collection<A> {... Excellent tutorial listed on references page But they didn t change the JVM to add generics How was that done? Translation via Erasure Replace uses of type variables with Object class A<T> {...T x;... becomes class A {...Object x;... Add downcasts wherever necessary Integer x = A<Integer>.get(); becomes Integer x = (Integer) (A.get()); So why did we bother with generics if they re just going to be removed? Because the compiler still did type checking for us We know that those casts will not fail at run time CMSC 330 23 CMSC 330 24 6

Limitations of Translation Some type information not available at compiletime Recall type variables T are rewritten to Object Disallowed, assuming T is type variable new T() would translate to new Object() (error) new T[n] would translate to new Object[n] (warning) Some casts/instanceofs that use T Ø Only ones the compiler can figure out are allowed Using with Legacy Code Translation via type erasure class A <T> becomes class A Thus class A is available as a raw type class A<T> {... class B { A x; // use A as raw type Sometimes useful with legacy code, but... Dangerous feature to use, plus unsafe Relies on implementation of generics, not semantics CMSC 330 25 CMSC 330 26 Subtyping and Arrays Java has one funny subtyping feature If S is a subtype of T, then S[ ] is a subtype of T[ ] Let s write methods that take arbitrary arrays public static void reversearray(object [] A) { for(int i=0, j=a.length-1; i<j; i++,j--) { Object tmp = A[i]; A[i] = A[j]; A[j] = tmp; CMSC 330 27 Problem with Subtyping Arrays public class A {... public class B extends A { void newmethod();... void foo(void) { B[] bs = new B[3]; A[] as; as = bs; // Since B[] subtype of A[] as[0] = new A(); // (1) bs[0].newmethod(); // (2) Fails since not type B Program compiles without warning Java must generate run-time check at (1) to prevent (2) Type written to array must be subtype of array contents CMSC 330 28 7

Subtyping for Generics Is Stack<Integer> a subtype of Stack<Object>? We could have the same problem as with arrays Thus Java forbids this subtyping Now consider the following method: int count(collection<object> c) { int j = 0; for (Iterator<Object> i = c.iterator(); i.hasnext(); ) { Object e = i.next(); j++; return j; Solution I: Use Polymorphic Methods <T> int count(collection<t> c) { int j = 0; for (Iterator<T> i = c.iterator(); i.hasnext(); ) { T e = i.next(); j++; return j; But requires a dummy type variable that isn t really used for anything Ø Not allowed to call count(x) where x has type Stack<Integer> CMSC 330 29 CMSC 330 30 Solution II: Wildcards Use? as the type variable Collection<?> is Collection of unknown int count(collection<?> c) { int j = 0; for (Iterator<?> i = c.iterator(); i.hasnext(); ) { Object e = i.next(); j++; return j; Legal Wildcard Usage Reasonable question: Stack<Integer> is not a subtype of Stack<Object> Why is Stack<Integer> a subtype of Collection<?>? Answer: Wildcards permit reading but not writing Why is this safe? Using? is a contract that you ll never rely on having a particular parameter type All objects subtype of Object, so assignment to e ok CMSC 330 31 CMSC 330 32 8

Example: Can Read But Cannot Write c int count(collection<?> c) { int j = 0; for (Iterator<?> i = c.iterator(); i.hasnext(); ) { Object e = i.next(); c.add(e); // fails: Object is not? j++; return j; For Loops Java 1.5 has a more convenient syntax for this standard for loop int count(collection<?> c) { int j = 0; for (Object e : c) j++; return j; This loop will get the standard iterate and set e to each element of the list, in order CMSC 330 33 CMSC 330 34 More on Generic Classes Suppose we have classes Circle, Square, and Rectangle, all subtypes of Shape void drawall(collection<shape> c) { for (Shape s : c) s.draw(); Can we pass this method a Collection<Square>? Ø No, not a subtype of Collection<Shape> How about the following? void drawall(collection<?> c) { for (Shape s : c) s.draw(); // not allowed, assumes? is Shape CMSC 330 35 Bounded Wildcards We want drawall to take a Collection of anything that is a subtype of shape this includes Shape itself void drawall(collection<? extends Shape> c) { for (Shape s : c) s.draw(); This is a bounded wildcard We can pass Collection<Circle> We can safely treat s as a Shape CMSC 330 36 9

Upper Bounded Wild Cards? extends Shape actually gives an upper bound on the type accepted Shape is the upper bound of the wildcard Bounded Wildcards (cont.) Should the following be allowed? void foo(collection<? extends Shape> c) { c.add(new Circle()); Circle Shape Rectangle No, because c might be a Collection of something that is not compatible with Circle This code is forbidden at compile time Square CMSC 330 37 CMSC 330 38 Lower Bounded Wildcards Dual of the upper bounded wildcards? super Rectangle denotes a type that is a supertype of Rectangle Type Rectangle is included? super Rectangle gives a lower bound on the type accepted Shape Lower Bounded Wildcards (cont.) Now the following is allowed void foo(collection<? super Circle> c) { c.add(new Circle()); c.add(new Rectangle()); // fails Because c is a Collection of something that is always compatible with Circle Rectangle Circle Square CMSC 330 39 CMSC 330 40 10

Bounded Type Variables You can also add bounds to regular type vars <T extends Shape> T getanddrawshape(list<t> c) { c.get(1).draw(); return c.get(2); This method can take a List of any subclass of Shape Ø This addresses some of the reason that we decided to introduce wild cards Ø Once again, this only works for methods CMSC 330 41 11