Sie sind auf Seite 1von 31

Polymorphism

Anabel Paredes
Alexander Pinto
Victor Reyna
David Roque
Polymorphic subprogram

- Software reuse can be an important contributor to software productivity.


One way to increase the reusability of software is to lessen the need to
create different subprograms that implement the same algorithm on
different types of data.
- Polymorphic subprogram takes parameters of different types on
different activations.
Ad hoc Polymorphism
- Overloaded subprograms provide a particular kind of polymorphism
called ad hoc polymorphism.
- Overloaded subprograms need not behave similarly.
C++
Java
- Overloaded subprograms that have default parameters can lead to
ambiguous subprogram calls.

if no method’s parameter profile matches the number and types of the actual
parameters in a method call, but two or more methods have parameter profiles that
can be matched through coercions, which method should be called?

the designer decide how to rank all of the different coercions, so that the
compiler can choose the method that “best” matches the call.
Subtype polymorphism
- Run-time Polymorphism
- A variable of type T can access any object of type T or any type derived
from T.
C++

A more general kind of polymorphism is provided by the methods of


Python and Ruby. Recall that variables in these languages do not have types, so
formal parameters do not have types.
Parametric polymorphism

- Compile-Time Polymorphism
- Parametric polymorphism is provided by a subprogram that takes generic
parameters that are used in type expressions that describe the types of
the parameters of the subprogram. Different instantiations of such
subprograms can be given different generic parameters, producing
subprograms that take different types of parameters.
- Parametrically polymorphic subprograms are often called generic
subprograms.
Java
C++
Dynamic binding (dispatch)
- Abstract data types, inheritance.
- Kind of polymorphism provided by the dynamic binding of messages to
method definitions.
Problems and purpose.
- Run-time system must determine, during execution, which method
should be called, A’s or B’s?,
- Determining which type object is currently referenced by the reference.
- One purpose of dynamic binding is to allow software systems to be more
easily extended during both development and maintenance. (Car Catalog
example).
Abstract (base) Class.
● The design of an inheritance hierarchy results in a class that are so high in
the hierarchy that an instantiation would not make sense.
● It probably would not make sense to have an implemented a method in
base class. But because all of its descendant classes should have such an
implemented method, the protocol (but not the body) of that method is
included in Base. (Pure virtual method in C++).
● A class that includes at least one abstract method is called an abstract
class (abstract base class in C++). Such a class usually cannot be
instantiated, because some of its methods are declared but are not
defined (they do not have bodies).
C++
Objective-C
● There is no way to
prevent overriding of
an inherited method.
● Support for
polymorphism with its
id data type is
overkill, for it allows
variables to reference
any object, rather
than just those in an
inheritance line.
Java
In C++, a method must be defined as virtual to allow dynamic binding. In Java,

all method calls are dynamically bound unless the called method has been

defined as final, in which case it cannot be overridden and all bindings are

static. Static binding is also used if the method is static or private, both of

which disallow overriding.


C#
Relación entre subtipos y la herencia.
A number of issues must be considered when designing the programming language
features to support inheritance and dynamic binding.

A) The Exclusivity of Objects

Advantage:

- Elegance and pure uniformity of the language and its use.

Disadvantage:

- (Principal) simple operations must be done through the


message-passing process, which often makes them slower than
similar operations in an imperative model, where single machine
instructions implement such simple operations.
A) The Exclusivity of Objects

- In this purest model of object-oriented computation, all types are classes. There is no
distinction between predefined and user-defined classes.

Alternativas:

- Conservar la colección completa de los Resultará en un lenguaje más


tipos del lenguaje base imperativo y amplio cuya estructura tipográfica
añadir el modelo de escritura de puede ser confusa para los nuevos
objetos. usuarios del lenguaje.
Alternativas:

- Tener una estructura tipográfica Permitirá que la velocidad de las


de estilo imperativo para los tipos operaciones sobre valores
escalares primitivos, pero primitivos sea comparable a la
implementar todos los tipos esperada en el modelo imperativo.
estructurados como objetos.
B) Are Subclasses Subtypes?

Principle of substitution

Si un lenguaje permite programas en los que una variable de una clase puede
ser sustituida por una variable de una de sus clases ancestrales, sin presentar
problemas comos los siguientes:

- Errores tipográficos
- Cambios en el comportamiento del programa.

Subtype

B es un subtipo de A si la clase B se deriva de la clase A, entonces B tiene todo


lo que tiene A y el comportamiento de un objeto de la clase B , cuando se utiliza
en lugar de un objeto de la clase A, resultan idénticos.
C) Single and Multiple Inheritance?

Does the language allow multiple inheritance (in addition to single inheritance)?

multiple propósito allow a new class


inheritance to inherit from two or
more classes.

Why would a language designer not


include it?

- Complexity

Ambiguity problem when the


two parent classes both define
identically named methods and
one or both of them must be
overridden in the subclass.
- Efficiency
En C++, por ejemplo, el soporte de herencia múltiple requiere:

● sólo un acceso adicional al array y


● una operación adicional para cada llamada a un método ligado
dinámicamente.

El costo adicional por la herencia múltiple es pequeño.

Maintenance of systems that use


multiple inheritance can be a
more serious problem, for
multiple inheritance leads to
more complex dependencies
among classes!
- Dynamic and Static Binding

● La vinculación dinámica de los mensajes a los métodos es una parte


esencial de la programación orientada a objetos.

● La cuestión aquí es si todos los enlaces de mensajes a los métodos


son dinámicos.

● La alternativa es permitir que el usuario especifique si un enlace


específico debe ser dinámico o estático.

The advantage of this


is that static bindings
are faster.
- Nested classes:

Information
hiding
Motivation

If a new class is needed by only one class, there is no reason to define it so it


can be seen by other classes. In this situation, the new class can be nested
inside the class that uses it.
Implementation of Object-Oriented
Constructs

- Instance Data Storage


- Dynamic Binding of Method Calls to Methods
Instance Data Storage

Class Instance Record (CIR).

- CIR is static
- Built at compile time
- Template for the creation of the data of class instances
Dynamic Binding of Method Calls to
Methods
Methods that will be dynamically bound must have entries in this CIR

1 Solution. Each CIR must have a pointer to methods

2 Solution. Vtable (virtual method table).


GRACIAS

Das könnte Ihnen auch gefallen