Polymorphism Chapter EightModern Programming Languages1.

Slides:



Advertisements
Similar presentations
Modern Programming Languages, 2nd ed.
Advertisements

ISBN Chapter 7 Expressions and Assignment Statements.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
5/15/2015IT 3271 Polymorphism (Ch 8) n A functions that is not fixed is polymorphic n Applies to a wide variety of language features n Most languages have.
Chapter EightModern Programming Languages1 Polymorphism.
Polymorphism Chapter EightModern Programming Languages1.
COEN Expressions and Assignment
Type Checking.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
ISBN Chapter 7 Expressions and Assignment Statements.
1 Chapter 7: Expressions Expressions are the fundamental means of specifying computations in a programming language To understand expression evaluation,
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
1 Names, Scopes and Bindings. 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables,
ISBN Chapter 9 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Introduction Two fundamental abstraction facilities.
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
ISBN Chapter 7 Expressions and Assignment Statements.
Expressions, Evaluation and Assignments
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Operator Overloading and Type Conversions
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Copyright © 1998 by Addison -Wesley Longman, Inc. 1 Chapter 6 Arithmetic Expressions - Their evaluation was one of the motivations for the development.
1-1 University of Hail College of Computer Science and Engineering Department of computer Science and Software Engineering Course: ICS313: Fundamentals.
7-1 Chapter 7: Expressions and Assignment Statements Arithmetic Expressions –the fundamental means of specifying computations in a programming language.
CS 363 Comparative Programming Languages Expressions and Assignment Statements.
C H A P T E R S E V E N Expressions and Assignment Statements.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Chapter EightModern Programming Languages1 Polymorphism.
CSI 3120, Expressions and assignment, page 1 Expressions and assignment Points for discussion Arithmetic expressions Overloading Logical expressions Assignment.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
CS212: Object Oriented Analysis and Design Lecture 9: Function Overloading in C++
Arithmetic Expressions
Expressions and Assignment Statements
ISBN Chapter 7 Expressions and Assignment Statements.
Chapter 7 © 1998 by Addison -Wesley Longman, Inc Arithmetic Expressions - Their evaluation was one of the motivations for the development of the.
ISBN Chapter 7 Expressions and Assignment Statements.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
March 31, ICE 1341 – Programming Languages (Lecture #11) In-Young Ko Programming Languages (ICE 1341) Lecture #11 Programming Languages (ICE 1341)
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
Overview of C++ Polymorphism
1 CS Programming Languages Class 10 September 26, 2000.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
7-1/27 Chapter 7 Expressions and Assignment Statements Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
Expressions and Assignment Statements
Types Type Errors Static and Dynamic Typing Basic Types NonBasic Types
Polymorphism (Ch 8) Scope (Ch 10) Who are you? What do you do now?
7.2 Arithmetic Expressions
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment Statements
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment Statements
Expressions and Assignment Statements
Arithmetic Expressions
Expressions and Assignment Statements
College of Computer Science and Engineering
Chapter 7 Expressions and Assignment Statements.
Overview of C++ Polymorphism
PRESENTED BY ADNAN M. UZAIR NOMAN
Modern Programming Languages
Presentation transcript:

Polymorphism Chapter EightModern Programming Languages1

What is Polymorphism? Varying function behavior based on parameter types Objects are just parameters (“this”) Manifest in several ways! Chapter EightModern Programming Languages2

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter EightModern Programming Languages 3

Predefined Overloaded Operators Chapter EightModern Programming Languages 4 Pascal: a := 1 + 2; b := ; c := "hello " + "there"; d := ['a'..'d'] + ['f'] ML: val x = 1 + 2; val y = ;

Operator Overloading In C++ C++ allows virtually all operators to be overloaded, including: ◦ the usual operators ( +, -, *, /, %, ^, &, |, ~, !, =,, +=, -=,=, *=, /=, %=, ^=, &=, |=, >, >>=, =, &&, ◦ ||, ++, --, ->*,, ) ◦ dereferencing ( *p and p->x ) ◦ subscripting ( a[i] ) ◦ function call ( f(a,b,c) ) ◦ allocation and deallocation ( new and delete ) Chapter EightModern Programming Languages 5

Implementing Overloading Compilers usually implement overloading the same way: ◦ Create a set of monomorphic functions, one for each definition ◦ Invent a mangled name for each, encoding the type information ◦ Have each reference use the appropriate mangled name, depending on the parameter types Chapter EightModern Programming Languages 6

Example: C++ Implementation Chapter EightModern Programming Languages 7 int shazam(int a, int b) {return a+b;} double shazam(double a, double b) {return a+b;} shazam__Fii: lda $30,-32($30).frame $15,32,$26,0 … shazam__Fdd: lda $30,-32($30).frame $15,32,$26,0 … C++: Assembler:

When is Overloading Resolved? Chapter EightModern Programming Languages8

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter EightModern Programming Languages 9

Coercion A coercion is an implicit type conversion, supplied automatically even if the programmer leaves it out Chapter EightModern Programming Languages 10 double x; x = (double) 2; double x; x = 2; Explicit type conversion in Java: Coercion in Java:

Parameter Coercion Languages support different coercions in different contexts: assignments, other binary operations, unary operations, parameters… When a language supports coercion of parameters on a function call (or of operands when an operator is applied), the resulting function (or operator) is polymorphic Chapter EightModern Programming Languages 11

Example: Java Chapter EightModern Programming Languages 12 void f(double x) { … } f((byte) 1); f((short) 2); f('a'); f(3); f(4L); f(5.6F); This f can be called with any type of parameter Java is willing to coerce to type double

Defining Coercions Language definitions often take many pages to define exactly which coercions are performed Some languages, especially some older languages like Algol 68 and PL/I, have very extensive powers of coercion Some, like ML, have none Most, like Java, are somewhere in the middle Chapter EightModern Programming Languages 13

Example: Java Chapter EightModern Programming Languages Unary Numeric Promotion Some operators apply unary numeric promotion to a single operand, which must produce a value of a numeric type: If the operand is of compile-time type byte, short, or char, unary numeric promotion promotes it to a value of type int by a widening conversion (§5.1.2). Otherwise, a unary numeric operand remains as is and is not converted. Unary numeric promotion is performed on expressions in the following situations: the dimension expression in array creations (§15.9); the index expression in array access expressions (§15.12); operands of the unary operators plus + (§ ) and minus - (§ )... The Java Language Specification James Gosling, Bill Joy, Guy Steele

Coercion and Overloading: Tricky Interactions There are potentially tricky interactions between overloading and coercion ◦ Overloading uses the types to choose the definition ◦ Coercion uses the definition to choose a type conversion Chapter EightModern Programming Languages 15

Example Suppose that, like C++, a language is willing to coerce char to int Which f gets called for f('a', 'b') ? Chapter EightModern Programming Languages 16 void f(int x, char y) { … } void f(char x, int y) { … }

User-Defined Coercion in C++ C++ allows conversion constructors: ◦ constructors that can be called with 1 arg ◦ the constructors coerces the argument type to the class type Suppose class A has the ctor A(B b) {…} ◦ And suppose function f takes an A: f(A a) {…} ◦ Then the call f(b) is well-defined This feature can be turned-off by making the constructor explicit: ◦ explicit A(B b) {…} Chapter EightModern Programming Languages17

User-Defined Coercion in C++ C++ allows conversion operators: ◦ member functions that convert the current object to another type ◦ these are called implicitly as needed class A { … operator B( ) const {…} }; x = a + b;// a.operator B( ) + b See convert.cpp Chapter EightModern Programming Languages18

When is Coercion Resolved? Chapter EightModern Programming Languages19

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter EightModern Programming Languages 20

Parametric Polymorphism A function exhibits parametric polymorphism if it has a type that contains one or more type variables A type with type variables is a polytype Found in languages including ML, C++ and Ada Chapter EightModern Programming Languages 21

Example: C++ Function Templates Chapter EightModern Programming Languages 22 template X max(X a, X b) { return a>b ? a : b; } void g(int a, int b, char c, char d) { int m1 = max(a,b); char m2 = max(c,d); } Note that > can be overloaded, so X is not limited to types for which > is predefined.

Example: ML Functions Chapter EightModern Programming Languages 23 - fun identity x = x; val identity = fn : 'a -> 'a - identity 3; val it = 3 : int - identity "hello"; val it = "hello" : string - fun reverse x = = if null x then nil = else (reverse (tl [(hd x)]; val reverse = fn : 'a list -> 'a list

Polymorphism and Operators Operators that prevent polymorphism in ML ◦ +, -, *, ~ ◦ /, div, mod ◦, >= ◦ andalso, orelse, not ◦ ^ ◦ Conversion functions (floor, chr, etc.) Operators that allow polymorphism ◦ # ◦ ::, hd, tl, [ ] ◦ =, <> Chapter EightModern Programming Languages 24

Implementing Parametric Polymorphism One extreme: many copies ◦ Create a set of monomorphic implementations, one for each type parameter the compiler sees  May create many similar copies of the code  Each one can be optimized for individual types The other extreme: one copy ◦ Create one implementation, and use it for all  True universal polymorphism: only one copy  Can’t be optimized for individual types Many variations in between Chapter EightModern Programming Languages 25

When are Type Parameters Resolved? Chapter EightModern Programming Languages26

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter EightModern Programming Languages 27

Subtype Polymorphism A function or operator exhibits subtype polymorphism if one or more of its parameter types have subtypes ◦ The declared type of the parameter is the static type ◦ The actual type of the runtime object is the dynamic type Important source of polymorphism in languages with a rich structure of subtypes ◦ Especially object-oriented languages Chapter EightModern Programming Languages 28

Exposing Dynamic Types Rarely done! See rtti.cpp Chapter EightModern Programming Languages29

Example: Java Chapter EightModern Programming Languages 30 class Car { void brake() { … } } class ManualCar extends Car { void clutch() { … } } void g(Car z) { z.brake(); } void f(Car x, ManualCar y) { g(x); g(y); } A subtype of Car is ManualCar Function g has an unlimited number of types—one for every class we define that is a subtype of Car That’s subtype polymorphism

Example: Pascal Chapter EightModern Programming Languages 31 type Day = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); Weekday = Mon..Fri; function nextDay(D: Day): Day; begin if D=Sun then nextDay:=Mon else nextDay:=D+1 end; procedure p(D: Day; W: Weekday); begin D := nextDay(D); D := nextDay(W) end; Subtype polymorphism: nextDay can be called with a subtype parameter

When are Subtypes Resolved? Chapter EightModern Programming Languages32

Outline Overloading Parameter coercion Parametric polymorphism Subtype polymorphism Definitions and classifications Chapter EightModern Programming Languages 33

Polymorphism We have seen four kinds of polymorphic functions There are many other uses of polymorphic: ◦ Polymorphic variables, classes, packages, languages ◦ Another name for runtime method dispatch: when x.f may call different methods depending on the runtime class of the object x Here are definitions that cover our four… Chapter EightModern Programming Languages 34

Definitions For Our Four A function or operator is polymorphic if it has at least two possible types ◦ It exhibits ad hoc polymorphism if it has at least two but only finitely many possible types  The number of applicable types is known in advance ◦ It exhibits universal polymorphism if it has infinitely many possible types (extensible)  New types may be easily added without changing any original code  No type-specific code appears in original Chapter EightModern Programming Languages 35

Overloading Ad hoc polymorphism Each different type requires an explicit definition in code Chapter EightModern Programming Languages 36

Parameter Coercion Ad hoc polymorphism The different types that can be coerced to a given parameter type is determined explicitly in code and by language definitions, as applicable Chapter EightModern Programming Languages 37

Parametric Polymorphism Universal polymorphism As long as the universe over which type variables are instantiated is locally unbounded A type unforeseen by the function’s developer can be employed ◦ Extended by the user Chapter EightModern Programming Languages 38

Subtype Polymorphism Universal As long as there is no limit to the number of different subtypes that can be declared for a given type True for all class-based object-oriented languages, like Java, C++, C#, etc. Chapter EightModern Programming Languages 39

Runtime vs. Compile-time Polymorphism Everything except subtype polymorphism is resolved at compile time ◦ the correctly typed functions are chosen by the compiler Subtype polymorphism uses late binding ◦ requires runtime overhead to resolve Chapter EightModern Programming Languages40

Static vs. Dynamic Languages Polymorphism is visible only in statically typed languages ◦ the compiler ensures that everything is type- safe Dynamically typed languages are by nature polymorphic (“duck typing”) ◦ see page 128 in text ◦ (first paragraph in 8.6) Chapter EightModern Programming Languages41