From Programming Languages: Principles and Paradigms, by Maurizio Gabbrielli, Simone Martini
Definition 8.5 A type system in which the same object can have more than one type is said to be polymorphic.
By analogy, we will say that the object is polymorphic when the type system assigns more than one type to it.
When an object is polymorphic, assume that it is assigned type T1 and type T2. Is it always true that one of two types T1 and T2 is a subset of the other? (Note that if you think it is not true, you can disprove it by giving a counterexample.)
If it is true, then can we say that polymorphism happens at the level of types which is more than at the level of objects, in the sense that, supposed T1 is a subset of T2, any object of T1 can also be assigned T2?
If it is not true, then can we say that polymorphism happens only at the level of objects, instead of the level of types, in the sense that, another object of T1 might not be assigned T2, and another object of T2 might not be assigned T1?
Thanks.
Example
If every object of type T2 is also of type T1, then T2 is a subtype of T1. THis means typically that T2 inherits from T1. Here a java example:
class T1
{
public void f() {
System.out.println ("hello I'm f() in T1");
}
}
class T2 extends T1
{
public void f() {
System.out.println ("hello I'm f() in T2");
}
}
...
T1 o = new T2();
o.f(); // behavior depends if o refers to a T1 or a T2.
...
Online demo
So object o in this example has two types: T2 and the inherited T1. Its behavior is definitively polymorphic.
Counter-example: this is not a generality
An object can have several types without necessarily one type being a subtype of another. Typically, you could have multiple inheritance, as in this C++ example:
class T1 {
public:
virtual void f() {
cout<<"I'm f() from T1"<<endl;
}
};
class T2 {
public:
virtual void f() {
cout<<"I'm f() from T2"<<endl;
}
virtual void g() {
cout<<"I'm g() from T2"<<endl;
}
};
class T3 : public T1, public T2 {
public:
void f() {
T2::f();
T1::f();
}
};
Here every o object that would be a T3 would also be a T1 and a T2 as well. There is a subset inclusion relationship between T1 and T3 and T2 and T3 but not between T1 and T2. So this seems to me a good counter-example of your general statement.
Live C++ example
Other considerations
You can't pretend that polymorphism happens only at the level of objects. At least not in strongly typed systems and with the definitions that you have given.
The object is however the cornerstone for polymorphism. For instance, in C++ you could have polymorphic types according to your definition, which would behave as if they would only have only one type depending on their context and the type with which they are referred to: simply remove the virtual
keyword from the C++ example above to see what happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With