What is polymorphism, what is it for, and how is it used?
What is Polymorphism, What is it For, and How is it Used?
What is Polymorphism?
Polymorphism is a key concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. The term comes from the Greek words "poly" (many) and "morph" (forms), meaning "many forms." In programming, it refers to the ability of a single interface or method to behave differently based on the object it is acting upon.
Types of Polymorphism
-
Compile-Time Polymorphism (Static Binding):
- Achieved through method overloading or operator overloading.
- The method to be executed is determined at compile time.
-
Run-Time Polymorphism (Dynamic Binding):
- Achieved through method overriding.
- The method to be executed is determined at runtime based on the actual object.
What is Polymorphism For?
-
Code Reusability:
- Allows writing generic and reusable code that works with objects of different types.
-
Extensibility:
- Makes it easier to add new functionality without modifying existing code.
-
Simplified Maintenance:
- Reduces code duplication and improves readability by leveraging common interfaces.
-
Flexibility:
- Enables objects to interact with each other more seamlessly, promoting loose coupling.
How is Polymorphism Used?
- Method Overloading (Compile-Time Polymorphism)
Method overloading allows multiple methods in the same class to have the same name but different parameter lists.
Example:
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // Output: 15 System.out.println(calc.add(5.5, 4.5)); // Output: 10.0
Explanation:
- The
add
method is overloaded, meaning it has multiple definitions with different parameter types. - The correct method is chosen at compile time based on the arguments.
- Method Overriding (Run-Time Polymorphism)
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Example in Python:
class Animal: def speak(self): return "Animal speaks" class Dog(Animal): def speak(self): return "Woof" class Cat(Animal): def speak(self): return "Meow" animals = [Dog(), Cat(), Animal()] for animal in animals: print(animal.speak())
Output:
Woof
Meow
Animal speaks
Explanation:
- Each class implements the
speak
method differently. - Polymorphism allows the
speak
method to behave differently depending on the type of object in the loop.
- Polymorphism with Interfaces or Abstract Classes
Polymorphism is often implemented using interfaces or abstract classes to define a common contract that different classes can implement or extend.
Example in Java:
interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { public void draw() { System.out.println("Drawing Rectangle"); } } Shape[] shapes = { new Circle(), new Rectangle() }; for (Shape shape : shapes) { shape.draw(); }
Output:
Drawing Circle
Drawing Rectangle
Explanation:
- The
Shape
interface defines a common contract (draw
method). - Both
Circle
andRectangle
provide their own implementations ofdraw
. - Polymorphism ensures the correct
draw
method is called for each object at runtime.
- Polymorphism with Function Parameters
Polymorphism allows you to design functions that can accept objects of different types and act on them through a common interface.
Example in Python:
class Car: def drive(self): return "Driving a car" class Truck: def drive(self): return "Driving a truck" def start_driving(vehicle): print(vehicle.drive()) start_driving(Car()) # Output: Driving a car start_driving(Truck()) # Output: Driving a truck
Explanation:
- The
start_driving
function accepts any object that has adrive
method. - Polymorphism ensures the correct implementation is invoked.
- Polymorphism in Collections
Polymorphism is frequently used in collections or arrays where elements may be of different types, but they share a common interface or superclass.
Example in Python:
class Shape: def area(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 shapes = [Circle(5), Square(4)] for shape in shapes: print(shape.area())
Output:
78.5
16
Explanation:
- Both
Circle
andSquare
inherit fromShape
and implement their ownarea
method. - Polymorphism ensures the correct
area
method is invoked for each object.
Summary
- Polymorphism allows one interface or method to handle multiple forms of behavior.
- Purpose: Enhances code reusability, extensibility, and flexibility while reducing complexity.
- Usage: Implemented through method overloading, method overriding, interfaces, abstract classes, and flexible function parameters. Polymorphism is a cornerstone of object-oriented programming, enabling systems to scale and adapt efficiently to changing requirements.
GET YOUR FREE
Coding Questions Catalog