SlideShare a Scribd company logo
1 of 20
Download to read offline
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

What's hot

The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an OverviewRoberto Casadei
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
1.2. introduction to automata theory
1.2. introduction to automata theory1.2. introduction to automata theory
1.2. introduction to automata theorySampath Kumar S
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming conceptPina Parmar
 
Context free languages
Context free languagesContext free languages
Context free languagesJahurul Islam
 
AI Propositional logic
AI Propositional logicAI Propositional logic
AI Propositional logicSURBHI SAROHA
 
Type Theory and Practical Application
Type Theory and Practical ApplicationType Theory and Practical Application
Type Theory and Practical ApplicationJack Fox
 
Computational logic Propositional Calculus proof system
Computational logic Propositional Calculus proof system Computational logic Propositional Calculus proof system
Computational logic Propositional Calculus proof system banujahir1
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classesteach4uin
 

What's hot (20)

The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
C vs c++
C vs c++C vs c++
C vs c++
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Theory of computation Lec2
Theory of computation Lec2Theory of computation Lec2
Theory of computation Lec2
 
1.2. introduction to automata theory
1.2. introduction to automata theory1.2. introduction to automata theory
1.2. introduction to automata theory
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming concept
 
Context free languages
Context free languagesContext free languages
Context free languages
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
AI Propositional logic
AI Propositional logicAI Propositional logic
AI Propositional logic
 
GCC compiler
GCC compilerGCC compiler
GCC compiler
 
Type Theory and Practical Application
Type Theory and Practical ApplicationType Theory and Practical Application
Type Theory and Practical Application
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
Why rust?
Why rust?Why rust?
Why rust?
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Computational logic Propositional Calculus proof system
Computational logic Propositional Calculus proof system Computational logic Propositional Calculus proof system
Computational logic Propositional Calculus proof system
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 

Viewers also liked

Conceitos básicos de orientação a objetos
Conceitos básicos de orientação a objetosConceitos básicos de orientação a objetos
Conceitos básicos de orientação a objetosSérgio Souza Costa
 
DBCells - an open and global multi-scale linked cells
DBCells - an open and global multi-scale linked cellsDBCells - an open and global multi-scale linked cells
DBCells - an open and global multi-scale linked cellsSérgio Souza Costa
 
Relações (composição e agregação)
Relações (composição e agregação)Relações (composição e agregação)
Relações (composição e agregação)Sérgio Souza Costa
 
Árvores: Conceitos e binárias
Árvores:  Conceitos e bináriasÁrvores:  Conceitos e binárias
Árvores: Conceitos e bináriasSérgio Souza Costa
 
Paradigma orientado a objetos - Caso de Estudo C++
Paradigma orientado a objetos - Caso de Estudo C++Paradigma orientado a objetos - Caso de Estudo C++
Paradigma orientado a objetos - Caso de Estudo C++Sérgio Souza Costa
 
Software Livre (Conceitos, contextualização histórica, licenças, sistemas ope...
Software Livre (Conceitos, contextualização histórica, licenças, sistemas ope...Software Livre (Conceitos, contextualização histórica, licenças, sistemas ope...
Software Livre (Conceitos, contextualização histórica, licenças, sistemas ope...Sérgio Souza Costa
 
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 7 - Inversão de ControleProgramação Orientada a Objetos - Pós Graduação - Aula 7 - Inversão de Controle
Programação Orientada a Objetos - Pós Graduação - Aula 7 - Inversão de ControleCarlos Eduardo
 
Programação Orientada a Objetos - Pós Graduação - Aula 2
Programação Orientada a Objetos - Pós Graduação - Aula 2Programação Orientada a Objetos - Pós Graduação - Aula 2
Programação Orientada a Objetos - Pós Graduação - Aula 2Carlos Eduardo
 
Programação Orientada a Objetos - Pós Graduação - Aula 6 - Princípios OO
Programação Orientada a Objetos - Pós Graduação - Aula 6 - Princípios OOProgramação Orientada a Objetos - Pós Graduação - Aula 6 - Princípios OO
Programação Orientada a Objetos - Pós Graduação - Aula 6 - Princípios OOCarlos Eduardo
 
Programação Orientada a Objetos - Pós Graduação - Aula 5 - refactoring com ho...
Programação Orientada a Objetos - Pós Graduação - Aula 5 - refactoring com ho...Programação Orientada a Objetos - Pós Graduação - Aula 5 - refactoring com ho...
Programação Orientada a Objetos - Pós Graduação - Aula 5 - refactoring com ho...Carlos Eduardo
 
Mini Curso - Programação de Interfaces Gráficas - aula 1
Mini Curso - Programação de Interfaces Gráficas - aula 1Mini Curso - Programação de Interfaces Gráficas - aula 1
Mini Curso - Programação de Interfaces Gráficas - aula 1Carlos Eduardo
 

Viewers also liked (20)

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

Similar to Polymorphism (Ad-hoc and Universal)

Polymorphism
PolymorphismPolymorphism
PolymorphismCME
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in JavaSonya Akter Rupa
 
7 probability and statistics an introduction
7 probability and statistics an introduction7 probability and statistics an introduction
7 probability and statistics an introductionThennarasuSakkan
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarAnimesh Sarkar
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in JavaDelowar Hossain
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالMahmoud Alfarra
 
Polymorphism in Python
Polymorphism in PythonPolymorphism in Python
Polymorphism in PythonTo Sum It Up
 
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCEDETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCEAbdurrahimDerric
 
Dependent Types for Cryptography Implementations
Dependent Types for Cryptography ImplementationsDependent Types for Cryptography Implementations
Dependent Types for Cryptography ImplementationsPaulo Silva
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13Vince Vo
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
Improving a Lightweight Stemmer for Gujarati Language
Improving a Lightweight Stemmer for Gujarati LanguageImproving a Lightweight Stemmer for Gujarati Language
Improving a Lightweight Stemmer for Gujarati Languageijistjournal
 
Data Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptxData Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptxR S Anu Prabha
 

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

Abstract classes and interfaces
Abstract classes and interfacesAbstract classes and interfaces
Abstract classes and interfaces
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
7 probability and statistics an introduction
7 probability and statistics an introduction7 probability and statistics an introduction
7 probability and statistics an introduction
 
Asp.net main
Asp.net mainAsp.net main
Asp.net main
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism in Python
Polymorphism in PythonPolymorphism in Python
Polymorphism in Python
 
Introduction to programming languages part 2
Introduction to programming languages   part 2Introduction to programming languages   part 2
Introduction to programming languages part 2
 
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCEDETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
 
Dependent Types for Cryptography Implementations
Dependent Types for Cryptography ImplementationsDependent Types for Cryptography Implementations
Dependent Types for Cryptography Implementations
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Oop in kotlin
Oop in kotlinOop in kotlin
Oop in kotlin
 
Improving a Lightweight Stemmer for Gujarati Language
Improving a Lightweight Stemmer for Gujarati LanguageImproving a Lightweight Stemmer for Gujarati Language
Improving a Lightweight Stemmer for Gujarati Language
 
Data Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptxData Structure and Algorithms –Introduction.pptx
Data Structure and Algorithms –Introduction.pptx
 
Typeful programming
Typeful programmingTypeful programming
Typeful programming
 

More from Sérgio Souza Costa

Expressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicasExpressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicasSérgio Souza Costa
 
De algoritmos à programas de computador
De algoritmos à programas de computadorDe algoritmos à programas de computador
De algoritmos à programas de computadorSérgio Souza Costa
 
Introdução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmosIntrodução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmosSérgio Souza Costa
 
Minicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficosMinicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficosSérgio Souza Costa
 
Banco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de EncerramentoBanco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de EncerramentoSérgio Souza Costa
 
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagemBanco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagemSérgio Souza Costa
 
Banco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de aberturaBanco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de aberturaSérgio Souza Costa
 
Linguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - IntroduçãoLinguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - IntroduçãoSérgio Souza Costa
 
Gödel’s incompleteness theorems
Gödel’s incompleteness theoremsGödel’s incompleteness theorems
Gödel’s incompleteness theoremsSérgio Souza Costa
 
Explorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento ComputacionalExplorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento ComputacionalSérgio Souza Costa
 
Aula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computaçãoAula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computaçãoSérgio Souza Costa
 
From remote sensing to agent-based models
From remote sensing to agent-based modelsFrom remote sensing to agent-based models
From remote sensing to agent-based modelsSérgio Souza Costa
 
Explorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficosExplorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficosSérgio Souza Costa
 

More from Sérgio Souza Costa (20)

Expressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicasExpressões aritméticas, relacionais e lógicas
Expressões aritméticas, relacionais e lógicas
 
De algoritmos à programas de computador
De algoritmos à programas de computadorDe algoritmos à programas de computador
De algoritmos à programas de computador
 
Introdução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmosIntrodução ao pensamento computacional e aos algoritmos
Introdução ao pensamento computacional e aos algoritmos
 
Minicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficosMinicurso de introdução a banco de dados geográficos
Minicurso de introdução a banco de dados geográficos
 
Modelagem de dados geográficos
Modelagem de dados geográficosModelagem de dados geográficos
Modelagem de dados geográficos
 
Banco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de EncerramentoBanco de dados geográfico - Aula de Encerramento
Banco de dados geográfico - Aula de Encerramento
 
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagemBanco de dados geográficos – Arquiteturas, banco de dados e modelagem
Banco de dados geográficos – Arquiteturas, banco de dados e modelagem
 
Banco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de aberturaBanco de dados geográficos - Aula de abertura
Banco de dados geográficos - Aula de abertura
 
Linguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - IntroduçãoLinguagem SQL e Extensões Espacias - Introdução
Linguagem SQL e Extensões Espacias - Introdução
 
Gödel’s incompleteness theorems
Gödel’s incompleteness theoremsGödel’s incompleteness theorems
Gödel’s incompleteness theorems
 
Turing e o problema da decisão
Turing e o problema da decisãoTuring e o problema da decisão
Turing e o problema da decisão
 
Introdução ao Prolog
Introdução ao PrologIntrodução ao Prolog
Introdução ao Prolog
 
Heap - Python
Heap - PythonHeap - Python
Heap - Python
 
Paradigma lógico
Paradigma lógicoParadigma lógico
Paradigma lógico
 
Contextualizando o moodle
Contextualizando o moodleContextualizando o moodle
Contextualizando o moodle
 
Explorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento ComputacionalExplorando Games para o Ensino do Pensamento Computacional
Explorando Games para o Ensino do Pensamento Computacional
 
Software
SoftwareSoftware
Software
 
Aula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computaçãoAula 1 - introdução a fundamentos de computação
Aula 1 - introdução a fundamentos de computação
 
From remote sensing to agent-based models
From remote sensing to agent-based modelsFrom remote sensing to agent-based models
From remote sensing to agent-based models
 
Explorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficosExplorando o HTML5 para visualização de dados geográficos
Explorando o HTML5 para visualização de dados geográficos
 

Recently uploaded

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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