Download presentation
Presentation is loading. Please wait.
Published byEarl Grant Modified over 9 years ago
1
Polymorphism CMPS 2143
2
Poly-morphism Means “many-forms” Means different things in biology, chemistry, computer science Means different things to functional language users and OOP language users Means there is ONE name, many different meanings ▫ Names: variables, functions, methods, class names ▫ Meanings: can be defined in different ways 2
3
Four forms of polymorphism Overloading Overriding Polymorphic variables Generics (templates) 3
4
Overloading – More in Chapter 15 AKA ad-hoc polymorphism Single function/method name has several alternative implementations Distinguished at compile time by type signature class myClass { public: //3 overloaded meanings for same name void example (int x) {…} void example (int x, double y) {…} void example (string x) {…} } 4
5
Overriding – More in Chapter 16 Single function/method name has several alternative implementations with the same signature, but occurs within context of the parent class/child class relationship class Parent { public: void example (int x) {…} } class Child { public: //same name, different method body void example (int x) {…} } 5
6
Polymorphic Variable – More in Chapter 17 AKA assignment polymorphism Variable is declared of one type, but holds a value of a different type //declared as parent, holding child value Room r = new King(…); When a polymorphic variable is used as an argument, the result function/method is said to exhibit pure polymorphism. 6
7
Generics/Templates – More in Chapter 18 A way of creating general purpose tools and specializing them to specific situations template T max (T left, T right){ if (left < right) return right; return left; } A generic function or class is parameterized by type ▫ Similar to the way a function is parameterized by values The type is unspecified, to be filled in later 7
8
Many tools, one goal Polymorphism is the feature of OOP languages that distinguish them the most from other types of languages Each different polymorphic technique permits a different form of reuse 8
9
Study questions Pg. 286: 2-5, 9 9
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.