Does polymorphism in programming languages ​​imply a subset of the relationships between the types involved?

From programming languages: principles and paradigms, by Maurizio Gabbrielli, Simone Martini

Definition 8.5 A type system in which one and the same object can have more than one type is called polymorphic.

By analogy, we say that an object is polymorphic when a system type assigns it more than one type.

When an object is polymorphic, suppose it is assigned type T1 and type T2. Is it always true that one of the two types T1 and T2 is a subset of the other? (Note: if you think this is not true, you can refute it by providing a counterexample.)

If this is true, then can we say that polymorphism occurs at the level of types, which is greater than at the level of objects, in the sense that prospective T1 is a subset of T2, can any object T1 be assigned to T2?

If this is not so, can we say that polymorphism occurs only at the level of objects, and not at the level of types, in the sense that T2 cannot be assigned to another object T1, and T1 can not be assigned to another T2?

Thanks.

+5
source share
1 answer

Example

If each object of type T2 also has type T1, then T2 is a subtype of T1. This means that T2 inherits from T1. Here is 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(); of(); // behavior depends if o refers to a T1 or a T2. ... 

online demo

Thus, the object o in this example has two types: T2 and inherited T1. His behavior is finally polymorphic.

Counter-example: this is not a generality

An object can have several types, not necessarily one type, which is a subtype of another. Generally, you can 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 T3 would also be T1 and T2. There is a relationship of including a subset between T1 and T3 and T2 and T3, but not between T1 and T2. So this seems like a good counter-example to your general statement.

Live C ++ Example

Other considerations

You cannot pretend that polymorphism occurs only at the level of objects. At least not in strongly typed systems and with the definitions you specified.

However, the object is the cornerstone for polymorphism. For example, in C ++, you can have polymorphic types according to your definition, which will behave as if they had only one type depending on their context and the type they refer to: just delete the virtual from the C ++ example above to find out what will happen.

+3
source

All Articles