![]() → 7įor values of type int, the addition function adds the two values together, so 3+4 returns 7. Return a value of their corresponding types, int and String, respectively. The Python addition function is an ad hoc polymorphism because it is a single function of the same name, “+”, that works on multiple types. Python is dynamically typed (it does not require the type to be specified). The code, which could be a parametric polymorphism function written in Python: for (element in list):įor ad hoc polymorphism, functions with the same name act differently for different types. A parametric polymorphism could remove, add, or replace elements of this list regardless of the element’s type. The function may look like this (not written in any specific programming language): getColor(BMW)Ī parametric polymorphism specifically provides a way to use one function (the same code) to interact with multiple types.Īn example would be a list of types. We can write a function to fetch the color of any one of the car subtypes. Each car has its property color.Īll subtypes can be referenced interchangeably by using class Car.Įvery car has a property, color, and now we can get the color from each subtype of the Car class. In the car example above, we create the object class, “Car”, and define multiple subtypes of it to be: Ford, Chevrolet, Kia, Nissan, Volkswagen, BMW, Audi, and Tesla. It is usually the one referenced when someone says, “The object is polymorphic.”Ī subtype polymorphism uses one class name to reference multiple kinds of subtypes at once. Subtype polymorphism is the most common kind of polymorphism. There are four main types of polymorphism:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |