Lecture: Polymorphism (CS 200)
Introduction to Polymorphism
- Polymorphism means 'many forms'.
- It allows objects to be treated as instances of their parent class.
- Enhances flexibility and reusability in OOP.
Polymorphism - Slide 1
Background Concepts
- Class: A blueprint for creating objects.
- Object: An instance of a class.
- Method: A function defined in a class.
- Encapsulation: Bundling of data and methods.
Polymorphism - Slide 2
Understanding Inheritance
- Inheritance allows one class to inherit attributes and methods from another.
- Base class (superclass) and derived class (subclass).
- Supports code reuse and hierarchical classification.
Polymorphism - Slide 3
Types of Polymorphism
- Compile-time (Static) Polymorphism: Achieved using method overloading.
- Run-time (Dynamic) Polymorphism: Achieved using method overriding.
Polymorphism - Slide 4
Example: Static Polymorphism
- class Math:
- def add(self, a, b): return a + b
- def add(self, a, b, c): return a + b + c # Example of overloading
Polymorphism - Slide 5
Example: Dynamic Polymorphism
- class Animal:
- def speak(self): print('Animal speaks')
- class Dog(Animal):
- def speak(self): print('Dog barks') # Overriding method
Polymorphism - Slide 6
Polymorphism with Inheritance
- class Shape: def area(self): pass
- class Circle(Shape): def area(self): return 3.14 * r * r
- class Rectangle(Shape): def area(self): return l * w
- Each subclass defines area() differently.
Polymorphism - Slide 7
Benefits of Polymorphism
- Code reusability.
- Improved readability and maintainability.
- Easier to manage and scale large applications.
Polymorphism - Slide 8
Attendance Quiz
- Q1: What is the key difference between overloading and overriding?
- Q2: Which type of polymorphism occurs at runtime?
- Q3: True/False - Inheritance is not necessary for polymorphism.
Polymorphism - Slide 9
Summary
- Polymorphism is a core principle of OOP.
- It enables flexibility and dynamic method execution.
- Understanding inheritance is key to mastering polymorphism.