POLYMORPHISM AND DYNAMIC BINDING
Inheritance
allows us to define flexible variables that can attach themselves to various objects during run time. This property of inheritance is known as polymorphism.Values used for a more specific purpose may be assigned to values of a less-specialized purpose but not the other way round. For example, if you ask for vegetables and you get just green vegetables that is fine, but if you specifically ask for green vegetables, if you receive a bowl of vegetables, (which may include red peppers, radishes etc.) that would not be acceptable.
Feature redefinition is the ability to redefine al or some of the features a class inherits from its parents. A redefinition may affect the class' type thereby replacing the original with a descendant. It may also affect the implementation, thereby replacing the original's routine with a new one.
Dynamic Binding occurs when a computation uses a redefined variable for its own computation. Dynamic binding increases a program's flexibility. Another advantage is that the variables do not need to be explicitly selected because the choice only occurs at run time. This sets Eiffel apart from languages that have similar technical approaches such as Ada or Pascal that need case instructions to distinguish variables.
Eiffel reconciles dynamic binding with static typing. In other words, dynamic binding guarantees that whenever more than one version of a routine is applicable, the version most directly adapted to the target object will be used. Static typing means that the compiler makes sure that there is at least one such version.
In order to control the power of redefinition, a mechanism known as Assertions is used. Preconditions and postconditions found in this feature limit the amount of freedom granted to eventual redefiners. These conditions ensure that the any redefined version must stay within the semantic boundaries set by the original assertions.
P: POLYGON; r: RECTANGLE
…
create p ; create r ;
…
if c then
p: = r
end
print (p.perimeter)
where the polymorphic assignment p:= r is valid because of the above rule. If condition c is false, p will be attached to an object of type POLYGON for the computation of p.perimeter, which will then use the polygon algorithm. Otherwise p will be attached to a rectangle and the computation will use the version redefined for RECTANGLE.