+ 5
Example of polymorphism with explanation
2 Réponses
+ 9
class animal
who_are_you: output("animal")
class dog(animal)
who_are_you : output("dog")
bark: output("wuff")
class cat(animal)
who_are_you: output("cat")
animals = animal[3]
/* an element of animals is an instance of animal or of a class which somehow inherits from animal
*/
animals[0] = new animal
animals[1] = new dog
animals[2] = new cat
main{
iterating animals{
call who_are_you()
}
}
--------output of this prog----
animal
dog
cat
-------- why that output------
in main the call of method who_are_you of an animal-typed variable leads to three different results.
The type of the variable determines, which methods must be possible to call.
the type of the assigned instance determines, how the method is processed.
The behavior of different method calls even if the same type of variable is called polymorphism.
this also explains, why class dog may not delete method who_are_you . in general a class cannot delete a public class from super.
Also you may NOT change the signature of a method inherited from superclass. In the whole tree the call of the same public method must be equal.
W.o this two rules polymorphism cannot exist.
a similiar but different technique is overloading of a method
0
₩₩₩×₩×₩+₩₩+₩1₩1₩+₩₩1₩1₩1₩₩1₩1₩1₩1₩1 = you