What is polymorphism, what is it for, and how is it used?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

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

  1. Compile-Time Polymorphism (Static Binding):

    • Achieved through method overloading or operator overloading.
    • The method to be executed is determined at compile time.
  2. 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?

  1. Code Reusability:

    • Allows writing generic and reusable code that works with objects of different types.
  2. Extensibility:

    • Makes it easier to add new functionality without modifying existing code.
  3. Simplified Maintenance:

    • Reduces code duplication and improves readability by leveraging common interfaces.
  4. Flexibility:

    • Enables objects to interact with each other more seamlessly, promoting loose coupling.

How is Polymorphism Used?

  1. 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.
  1. 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.
  1. 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 and Rectangle provide their own implementations of draw.
  • Polymorphism ensures the correct draw method is called for each object at runtime.
  1. 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 a drive method.
  • Polymorphism ensures the correct implementation is invoked.
  1. 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 and Square inherit from Shape and implement their own area 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.
TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which is the best online coding platform?
Which code is best for programming?
How do you solve system design problems?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.