Polimorfismo de inclusão

<aside> 💡 Para entender melhor sobre os diferentes tipos de polimorfismo leia On Understanding Types, Data Abstraction, and Polymorphism

</aside>

Este tipo de polimorfismo requer que os tipos sejam relacionados dentro de um hierarquia de classes. Por exemplo:

Circle c = pc; // Assigned to a Circle variable without casting

<aside> 💡 Cada objeto PlaneCircle também é um objeto Círculo perfeitamente válido. Se pc se refere a um objeto PlaneCircle, podemos atribuí-lo a uma variável Circle . Esse é o princípio básico para o polimorfismo de inclusão, como veremos mais a frente

</aside>

Uma definição simples para polimorfismo de inclusão é encontrada em (Grady Brooch. Object-Oriented Analysis and Design with Applications. 1993)

When a name denotes instances of many different classes related by some common superclass.

Em termos de código, podemos considerar as seguintes classes:

class Geometry {
        protected double x, y;
        public void draw () {. . .} 
        ...       
class Circle extends Geometry {
        private double r;
        ...
class Rectangle extends Geometry {
        private double w, h;
        ...

Então, em uma aplicação poderíamos ter um mesmo nome (geo) associado a instâncias de diferentes tipos (Rectangle e Circle) desde que relacionado por uma mesma super classe (Geometry).

Geometry geo;
...
geo = new Rectangle (3.0, 4.0);
...
geo = new Circle(3.0, 4.0, 5.0);


Outra definição mais completa é encontrada em (David Watt):

“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”.

Ainda segundo o mesmo autor:

“Inclusion polymorphism is a key concept, enabling an object of a subclass to be treated like an object of its superclass. This allows us, for instance, to build a heterogeneous collection of objects of different classes, provided that the collection is defined in terms of some common ancestor class”.

Uma definição dada por Kim Bruce:

“Because values may have multiple types in languages supporting subtyping, we say these languages support subtype polymorphism. If v has type T, subtype polymorphism allows it to be used in any context that expects a value of some type U as long as T is a subtype of U.”

Aproveitando o mesmo exemplo anterior:

...
List<Geometry> l = new LinkedList<Geometry>();
// insere os elementos
...
// desenha todas geometrias
for (Geometry geo: l) {
    geo.draw(); // essa parte da aplicação não precisa saber qual a instãncia
}