SlideShare a Scribd company logo
Polymorphism (Ad-hoc and Universal
Sérgio Souza Costa
Universidade Federaldo Maranhão
3 de julho de 2016
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 1 / 20
Based in On understanding types, data abstraction, and polymorphism (Luca Cardelli and Peter
Wegner)
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 2 / 20
Summary
Static and Strong Typing
Polymorphism
Kinds of Polymorphism
Ad-hoc - Overloading
Ad-hoc - Coercion
Parametric polymorphism
Inclusion polymorphism
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 3 / 20
Static and Strong Typing
In mathematics as in programming, types impose constraints which help to enforce
correctness.
To prevent type violations, we generally impose a static type structure on programs. Types
are associated with constants, operators, variables, and function symbols.
A type inference system can be used to infer the types of expressions when little or no type
information is given explicitly.
In languages like Pascal and Ada, the type of variables and function symbols is defined by
redundant declarations and the compiler can check the consistency of definition and use.
In languages like ML, explicit declarations are avoided wherever possible and the system
may infer the type of expressions from local context, while still establishing
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 4 / 20
Static and Strong Typing
Definição
Programming languages in which the type of every expression can be determined by static
program analysis are said to be statically typed.
Static typing is a useful property, but the requirement that all variables and expressions are
bound to a type at compile time is sometimes too restrictive.
It may be replaced by the weaker requirement that all expressions are guaranteed to be
type-consistent although the type itself may be statically unknown; this can be generally
done by introducing some run-time type checking.
Definição
Languages in which all expressions are type-consistent are called strongly typed languages.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 5 / 20
Static and Strong Typing
Pros:
In general, we should strive for strong typing, and adopt static typing whenever possible..
Static typing allows type inconsistencies to be discovered at compile time and guarantees
that executed programs are type-consistent.
It facilitates early detection of type errors and allows greater execution-time efficiency. It
enforces a programming discipline on the programmer that makes programs more
structured and easier to read.
Cons:
Static typing may also lead to a loss of flexibility and expressive power by prematurely
constraining the behavior of objects to that associated with a particular type.
Traditional statically typed systems exclude programming techniques which, although
sound, are incompatible with early binding of program objects to a specific type. For
example they exclude generic procedures, e.g. sorting, that capture the structure of an
algorithm uniformly applicable to a range of types.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 6 / 20
Polymorphism
Conventional typed languages, such as Pascal, are based on the idea that functions and
procedures, and hence their operands, have a unique type. Such languages are said to be
monomorphic, in the sense that every value and variable can be interpreted to be of
one and only one type.
Polymorphic languages in which some values and variables may have more than one
type.
Polymorphic functions are functions whose operands (actual parameters) can have more
than one type.
Polymorphic types are types whose operations are applicable to values of more than one
type.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 7 / 20
Kinds of Polymorphism
Cardelli classification
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 8 / 20
Kinds of Polymorphism
Ad-hoc polymorphism is obtained when a function works, or appears to work, on
several different types (which may not exhibit a common structure) and may behave in
unrelated ways for each type.
Universally polymorphic functions will normally work on an infinite number of types
(all the types having a given common structure), while an ad-hoc polymorphic function
will only work on a finite set of different and potentially unrelated types.
In terms of implementation, a universally polymorphic function will execute the same
code for arguments of any admissible type, while an ad-hoc polymorphic function may
execute different code for each type of argument.
Universal polymorphism is considered true polymorphism, while ad-hoc polymorphism is
some kind of apparent polymorphism
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 9 / 20
Ad-hoc - Overloading
In overloading the same variable name is used to denote different functions, and the
context is used to decide which function is denoted by a particular instance of the name.
Example (c++):
1 main(){
2 int a = 2, b = 3;
3 float x = 1.5, y = 3.4;
4 a = a + b; // a = somaint (a, b);
5 x = x + y; // x = somafloat (x, y);
6 }
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 10 / 20
Ad-hoc - Coercion
A coercion is instead a semantic operation which is needed to convert an argument to the
type expected by a function, in a situation which would otherwise result in a type error.
Coercions can be provided statically, by automatically inserting them between arguments
and functions at compile time, or may have to be determined dynamically by run-time
tests on the arguments.
Implicit conversion between types.
Example (c++):
1 main() {
2 int w = 3;
3 float x;
4 float y = 5.2;
5 x = x + y; // x = somafloat (x, y)
6 x = x + w; // x = somafloat (x, intToFloat (w) );
7 }
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 11 / 20
Universal - Parametric polymorphism
Definição
In parametric polymorphism, a polymorphic function has an implicit or explicit type parameter,
which determines the type of the argument for each application of that function.
Example in Java
class Comparators {
public static <T extends Comparable<T>> T max (T a, T b) {
if (a.compareTo(b) > 0) return a;
else return b;
}
}
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 12 / 20
Universal - Parametric polymorphism
C++
1 template <class T>
2 T maior (T a, T b) {
3 return ( (a>b)? a : b );
4 }
Haskell
1 maior :: (Ord a) => a -> a -> a
2 maior a b
3 | a > b = a
4 | otherwise = b
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 13 / 20
Universal - Parametric polymorphism
The functions that exhibit parametric polymorphism are also called generic functions.
For example, the length function from lists of arbitrary type to integers is called a generic
length function.
1 length :: [a] -> Int
A generic function is one which can work for arguments of many types, generally doing the
same kind of work independently of the argument type.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 14 / 20
Universal - Parametric polymorphism
Parametric type and operator overloading
1 template <class T>
2 class Point {
3 public:
4 T x, y;
5 Point (T x1, T y1):x(x1),y(y1) {}
6 Point operator + (Point& other) {
7 return Point (x+other.x,y+other.y);
8 }
9 friend ostream& operator << (ostream& out, Point p) {
10 out << p.x << "-" << p.y << endl;
11 return out;
12 }
13 };
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 15 / 20
Universal - Parametric polymorphism
1 int main() {
2 Point<string> p1("ab","cd");
3 Point<string> p2("fg","de");
4 Point<string> p3 = p1 + p2;
5
6 cout << p3 << endl;
7
8 return 0;
9 }
Observação
Parametric polymorphism is supported in Java through Generic Types.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 16 / 20
Inclusion polymorphism
Definição
Inclusion polymorphism is a type system in which a type may have subtypes, which inherit
operations from that type. Where a type T is a set of values, equipped with some operations.
A subtype of T is a subset of the values of T, equipped with the same operations as T. Every
value of the subtype is also a value of type T, and therefore may be used in a context where a
value of type T is expected (David Watt).
In inclusion polymorphism an object can be viewed as belonging to many different classes
which need not be disjoint, i.e. there may be inclusion of classes.
Inclusion polymorphism as a relation among types which allows operations to be applied to
object of different types related by inclusion.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 17 / 20
Inclusion polymorphism - Example
class Point {
protected double x, y;
public void draw () {. . .} // Draw this point.
. . . // other methods
class Circle extends Point {
private double r;
public void draw () {. . .} //Draw this circle.
. . . // other methods
class Rectangle extends Point {
private double w, h;
public void draw () {. . .} // Draw this rectangle.
. . . // other methods
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 18 / 20
Inclusion polymorphism - Example
Java allows objects of any subclass to be treated like objects of the superclass. Consider
the following variable:
Point p;
...
p = new Point(3.0, 4.0);
...
p = new Circle(3.0, 4.0, 5.0);
This variable may refer to an object of class Point or any subclass of Point. In other
words, this variable may refer to any value of type Point.
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 19 / 20
Inclusion polymorphism - Example
Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 20 / 20

More Related Content

PPTX
Cohesion and coupling
PPTX
Databases in Android Application
PPTX
2CPP11 - Method Overloading
PPT
9. Input Output in java
PPT
4. system models
PPTX
Principles of Network Security-CIAD TRIAD
PPTX
Structure in c#
PPTX
Design Patterns - General Introduction
Cohesion and coupling
Databases in Android Application
2CPP11 - Method Overloading
9. Input Output in java
4. system models
Principles of Network Security-CIAD TRIAD
Structure in c#
Design Patterns - General Introduction

What's hot (20)

PPTX
Ch26 - software engineering 9
PPTX
Coupling , Cohesion and there Types
DOCX
BANKER'S ALGORITHM
PPTX
Software engineering project management
PPT
Oomd unit1
PPTX
Concurrency Control in Distributed Database.
PDF
Operating system 3
PPTX
Lec 7 query processing
PDF
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
PPTX
XML DTD DOCUMENT TYPE DEFINITION
PPTX
Temporal databases
PPTX
Strings,patterns and regular expressions in perl
DOCX
Locking base concurrency control
PPT
Basic concept of OOP's
PPTX
Linked stacks and queues
PPT
Deadlock management
PPSX
C lecture 4 nested loops and jumping statements slideshare
PPT
11 constructors in derived classes
PDF
Sucet os module_4_notes
PPTX
Association agggregation and composition
Ch26 - software engineering 9
Coupling , Cohesion and there Types
BANKER'S ALGORITHM
Software engineering project management
Oomd unit1
Concurrency Control in Distributed Database.
Operating system 3
Lec 7 query processing
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
XML DTD DOCUMENT TYPE DEFINITION
Temporal databases
Strings,patterns and regular expressions in perl
Locking base concurrency control
Basic concept of OOP's
Linked stacks and queues
Deadlock management
C lecture 4 nested loops and jumping statements slideshare
11 constructors in derived classes
Sucet os module_4_notes
Association agggregation and composition
Ad

Viewers also liked (20)

PDF
Conceitos básicos de orientação a objetos
PDF
DBCells - an open and global multi-scale linked cells
PDF
Herança e Encapsulamento
PDF
Relações (composição e agregação)
PDF
Comandos e expressões
PDF
Árvores: Conceitos e binárias
PDF
Funções e procedimentos
PDF
Paradigma orientado a objetos - Caso de Estudo C++
PDF
Google apps script - Parte - 1
PDF
Google apps script - Parte 2
PDF
Árvores balanceadas - AVL
PDF
Software Livre (Conceitos, contextualização histórica, licenças, sistemas ope...
PDF
Paradigmas de programação
ODP
php 01 introducao
PDF
Programação Orientada a Objetos - Pós Graduação - Aula 7 - Inversão de Controle
PDF
Programação Orientada a Objetos - Pós Graduação - Aula 2
PDF
Programação Orientada a Objetos - Pós Graduação - Aula 6 - Princípios OO
PDF
Programação Orientada a Objetos - Pós Graduação - Aula 5 - refactoring com ho...
PDF
Mini Curso - Programação de Interfaces Gráficas - aula 1
ODT
Java Lista Exercicios 04
Conceitos básicos de orientação a objetos
DBCells - an open and global multi-scale linked cells
Herança e Encapsulamento
Relações (composição e agregação)
Comandos e expressões
Árvores: Conceitos e binárias
Funções e procedimentos
Paradigma orientado a objetos - Caso de Estudo C++
Google apps script - Parte - 1
Google apps script - Parte 2
Árvores balanceadas - AVL
Software Livre (Conceitos, contextualização histórica, licenças, sistemas ope...
Paradigmas de programação
php 01 introducao
Programação Orientada a Objetos - Pós Graduação - Aula 7 - Inversão de Controle
Programação Orientada a Objetos - Pós Graduação - Aula 2
Programação Orientada a Objetos - Pós Graduação - Aula 6 - Princípios OO
Programação Orientada a Objetos - Pós Graduação - Aula 5 - refactoring com ho...
Mini Curso - Programação de Interfaces Gráficas - aula 1
Java Lista Exercicios 04
Ad

Similar to Polymorphism (Ad-hoc and Universal) (20)

PDF
Abstract classes and interfaces
PPTX
Polymorphism
 
PPTX
Method Overloading in Java
PDF
7 probability and statistics an introduction
PDF
Asp.net main
PDF
Polymorphism in Java by Animesh Sarkar
PDF
COSC3054 Lec 05 - Semantic Analysis and Type checking B.pdf
PPTX
Method Overloading in Java
PPTX
Basic concept of class, method , command line-argument
PPT
البرمجة الهدفية بلغة جافا - تعدد الأشكال
PPTX
Polymorphism
PPTX
Polymorphism in Python
PPT
Introduction to programming languages part 2
PDF
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
PDF
Dependent Types for Cryptography Implementations
PDF
谷歌留痕👉seo233.com👈
PDF
谷歌留痕👉seo233.com👈
PDF
ismm2009.pdfismm2009.pdfismm2009.pdfismm2009.pdfismm2009.pdfismm2009.pdf
Abstract classes and interfaces
Polymorphism
 
Method Overloading in Java
7 probability and statistics an introduction
Asp.net main
Polymorphism in Java by Animesh Sarkar
COSC3054 Lec 05 - Semantic Analysis and Type checking B.pdf
Method Overloading in Java
Basic concept of class, method , command line-argument
البرمجة الهدفية بلغة جافا - تعدد الأشكال
Polymorphism
Polymorphism in Python
Introduction to programming languages part 2
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
Dependent Types for Cryptography Implementations
谷歌留痕👉seo233.com👈
谷歌留痕👉seo233.com👈
ismm2009.pdfismm2009.pdfismm2009.pdfismm2009.pdfismm2009.pdfismm2009.pdf

More from Sérgio Souza Costa (20)

PDF
Expressões aritméticas, relacionais e lógicas
PDF
De algoritmos à programas de computador
PDF
Introdução ao pensamento computacional e aos algoritmos
PDF
Minicurso de introdução a banco de dados geográficos
PDF
Modelagem de dados geográficos
PPTX
Banco de dados geográfico - Aula de Encerramento
PDF
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
PDF
Banco de dados geográficos - Aula de abertura
PDF
Linguagem SQL e Extensões Espacias - Introdução
PDF
Gödel’s incompleteness theorems
PDF
Turing e o problema da decisão
PPTX
Introdução ao Prolog
PDF
Heap - Python
PDF
Paradigma lógico
PDF
Contextualizando o moodle
PDF
Explorando Games para o Ensino do Pensamento Computacional
PDF
PDF
Aula 1 - introdução a fundamentos de computação
PDF
From remote sensing to agent-based models
PDF
Explorando o HTML5 para visualização de dados geográficos
Expressões aritméticas, relacionais e lógicas
De algoritmos à programas de computador
Introdução ao pensamento computacional e aos algoritmos
Minicurso de introdução a banco de dados geográficos
Modelagem de dados geográficos
Banco de dados geográfico - Aula de Encerramento
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos - Aula de abertura
Linguagem SQL e Extensões Espacias - Introdução
Gödel’s incompleteness theorems
Turing e o problema da decisão
Introdução ao Prolog
Heap - Python
Paradigma lógico
Contextualizando o moodle
Explorando Games para o Ensino do Pensamento Computacional
Aula 1 - introdução a fundamentos de computação
From remote sensing to agent-based models
Explorando o HTML5 para visualização de dados geográficos

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Encapsulation theory and applications.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
1. Introduction to Computer Programming.pptx
PPTX
A Presentation on Touch Screen Technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
A comparative analysis of optical character recognition models for extracting...
Unlocking AI with Model Context Protocol (MCP)
1 - Historical Antecedents, Social Consideration.pdf
Encapsulation_ Review paper, used for researhc scholars
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
OMC Textile Division Presentation 2021.pptx
Encapsulation theory and applications.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
WOOl fibre morphology and structure.pdf for textiles
Chapter 5: Probability Theory and Statistics
SOPHOS-XG Firewall Administrator PPT.pptx
Hindi spoken digit analysis for native and non-native speakers
Digital-Transformation-Roadmap-for-Companies.pptx
Assigned Numbers - 2025 - Bluetooth® Document
gpt5_lecture_notes_comprehensive_20250812015547.pdf
A comparative study of natural language inference in Swahili using monolingua...
1. Introduction to Computer Programming.pptx
A Presentation on Touch Screen Technology
Programs and apps: productivity, graphics, security and other tools
A comparative analysis of optical character recognition models for extracting...

Polymorphism (Ad-hoc and Universal)

  • 1. Polymorphism (Ad-hoc and Universal Sérgio Souza Costa Universidade Federaldo Maranhão 3 de julho de 2016 Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 1 / 20
  • 2. Based in On understanding types, data abstraction, and polymorphism (Luca Cardelli and Peter Wegner) Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 2 / 20
  • 3. Summary Static and Strong Typing Polymorphism Kinds of Polymorphism Ad-hoc - Overloading Ad-hoc - Coercion Parametric polymorphism Inclusion polymorphism Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 3 / 20
  • 4. Static and Strong Typing In mathematics as in programming, types impose constraints which help to enforce correctness. To prevent type violations, we generally impose a static type structure on programs. Types are associated with constants, operators, variables, and function symbols. A type inference system can be used to infer the types of expressions when little or no type information is given explicitly. In languages like Pascal and Ada, the type of variables and function symbols is defined by redundant declarations and the compiler can check the consistency of definition and use. In languages like ML, explicit declarations are avoided wherever possible and the system may infer the type of expressions from local context, while still establishing Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 4 / 20
  • 5. Static and Strong Typing Definição Programming languages in which the type of every expression can be determined by static program analysis are said to be statically typed. Static typing is a useful property, but the requirement that all variables and expressions are bound to a type at compile time is sometimes too restrictive. It may be replaced by the weaker requirement that all expressions are guaranteed to be type-consistent although the type itself may be statically unknown; this can be generally done by introducing some run-time type checking. Definição Languages in which all expressions are type-consistent are called strongly typed languages. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 5 / 20
  • 6. Static and Strong Typing Pros: In general, we should strive for strong typing, and adopt static typing whenever possible.. Static typing allows type inconsistencies to be discovered at compile time and guarantees that executed programs are type-consistent. It facilitates early detection of type errors and allows greater execution-time efficiency. It enforces a programming discipline on the programmer that makes programs more structured and easier to read. Cons: Static typing may also lead to a loss of flexibility and expressive power by prematurely constraining the behavior of objects to that associated with a particular type. Traditional statically typed systems exclude programming techniques which, although sound, are incompatible with early binding of program objects to a specific type. For example they exclude generic procedures, e.g. sorting, that capture the structure of an algorithm uniformly applicable to a range of types. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 6 / 20
  • 7. Polymorphism Conventional typed languages, such as Pascal, are based on the idea that functions and procedures, and hence their operands, have a unique type. Such languages are said to be monomorphic, in the sense that every value and variable can be interpreted to be of one and only one type. Polymorphic languages in which some values and variables may have more than one type. Polymorphic functions are functions whose operands (actual parameters) can have more than one type. Polymorphic types are types whose operations are applicable to values of more than one type. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 7 / 20
  • 8. Kinds of Polymorphism Cardelli classification Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 8 / 20
  • 9. Kinds of Polymorphism Ad-hoc polymorphism is obtained when a function works, or appears to work, on several different types (which may not exhibit a common structure) and may behave in unrelated ways for each type. Universally polymorphic functions will normally work on an infinite number of types (all the types having a given common structure), while an ad-hoc polymorphic function will only work on a finite set of different and potentially unrelated types. In terms of implementation, a universally polymorphic function will execute the same code for arguments of any admissible type, while an ad-hoc polymorphic function may execute different code for each type of argument. Universal polymorphism is considered true polymorphism, while ad-hoc polymorphism is some kind of apparent polymorphism Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 9 / 20
  • 10. Ad-hoc - Overloading In overloading the same variable name is used to denote different functions, and the context is used to decide which function is denoted by a particular instance of the name. Example (c++): 1 main(){ 2 int a = 2, b = 3; 3 float x = 1.5, y = 3.4; 4 a = a + b; // a = somaint (a, b); 5 x = x + y; // x = somafloat (x, y); 6 } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 10 / 20
  • 11. Ad-hoc - Coercion A coercion is instead a semantic operation which is needed to convert an argument to the type expected by a function, in a situation which would otherwise result in a type error. Coercions can be provided statically, by automatically inserting them between arguments and functions at compile time, or may have to be determined dynamically by run-time tests on the arguments. Implicit conversion between types. Example (c++): 1 main() { 2 int w = 3; 3 float x; 4 float y = 5.2; 5 x = x + y; // x = somafloat (x, y) 6 x = x + w; // x = somafloat (x, intToFloat (w) ); 7 } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 11 / 20
  • 12. Universal - Parametric polymorphism Definição In parametric polymorphism, a polymorphic function has an implicit or explicit type parameter, which determines the type of the argument for each application of that function. Example in Java class Comparators { public static <T extends Comparable<T>> T max (T a, T b) { if (a.compareTo(b) > 0) return a; else return b; } } Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 12 / 20
  • 13. Universal - Parametric polymorphism C++ 1 template <class T> 2 T maior (T a, T b) { 3 return ( (a>b)? a : b ); 4 } Haskell 1 maior :: (Ord a) => a -> a -> a 2 maior a b 3 | a > b = a 4 | otherwise = b Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 13 / 20
  • 14. Universal - Parametric polymorphism The functions that exhibit parametric polymorphism are also called generic functions. For example, the length function from lists of arbitrary type to integers is called a generic length function. 1 length :: [a] -> Int A generic function is one which can work for arguments of many types, generally doing the same kind of work independently of the argument type. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 14 / 20
  • 15. Universal - Parametric polymorphism Parametric type and operator overloading 1 template <class T> 2 class Point { 3 public: 4 T x, y; 5 Point (T x1, T y1):x(x1),y(y1) {} 6 Point operator + (Point& other) { 7 return Point (x+other.x,y+other.y); 8 } 9 friend ostream& operator << (ostream& out, Point p) { 10 out << p.x << "-" << p.y << endl; 11 return out; 12 } 13 }; Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 15 / 20
  • 16. Universal - Parametric polymorphism 1 int main() { 2 Point<string> p1("ab","cd"); 3 Point<string> p2("fg","de"); 4 Point<string> p3 = p1 + p2; 5 6 cout << p3 << endl; 7 8 return 0; 9 } Observação Parametric polymorphism is supported in Java through Generic Types. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 16 / 20
  • 17. Inclusion polymorphism Definição Inclusion polymorphism is a type system in which a type may have subtypes, which inherit operations from that type. Where a type T is a set of values, equipped with some operations. A subtype of T is a subset of the values of T, equipped with the same operations as T. Every value of the subtype is also a value of type T, and therefore may be used in a context where a value of type T is expected (David Watt). In inclusion polymorphism an object can be viewed as belonging to many different classes which need not be disjoint, i.e. there may be inclusion of classes. Inclusion polymorphism as a relation among types which allows operations to be applied to object of different types related by inclusion. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 17 / 20
  • 18. Inclusion polymorphism - Example class Point { protected double x, y; public void draw () {. . .} // Draw this point. . . . // other methods class Circle extends Point { private double r; public void draw () {. . .} //Draw this circle. . . . // other methods class Rectangle extends Point { private double w, h; public void draw () {. . .} // Draw this rectangle. . . . // other methods Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 18 / 20
  • 19. Inclusion polymorphism - Example Java allows objects of any subclass to be treated like objects of the superclass. Consider the following variable: Point p; ... p = new Point(3.0, 4.0); ... p = new Circle(3.0, 4.0, 5.0); This variable may refer to an object of class Point or any subclass of Point. In other words, this variable may refer to any value of type Point. Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 19 / 20
  • 20. Inclusion polymorphism - Example Sérgio Souza Costa (Universidade Federaldo Maranhão) Paradigmas de Programação 3 de julho de 2016 20 / 20