Logo
Logo
Home
Archive
Advertise
YouTube
Login
Sign Up
  • Home
  • Posts
  • 🦥 OOP Pillar #4: Polymorphism For Dummies

🦥 OOP Pillar #4: Polymorphism For Dummies

Aug 20, 2024

Hello friends!

Welcome to this week’s Sloth Bytes.

I hope you had a good week 😁

Sloths are nocturnal

Giphy

Two-toed sloths are completely nocturnal. Although three-toed sloths are both diurnal and nocturnal, they’re largely inactive during the day.

OOP Pillar #4: Polymorphism

What is Polymorphism?

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface. (I stole it from here)

Why Polymorphism Matters

  • Increases code flexibility and reusability

  • Simplifies code structure

  • Enables more intuitive design of complex systems

  • Facilitates easier maintenance and scalability

Key Concepts:

  1. Method Overriding: Redefining a method in a subclass

  2. Method Overloading: Multiple methods with the same name but different parameters

  3. Interface Implementation: Different classes implementing the same interface

  4. Dynamic Method Dispatch: Runtime decision of which method to call

We can use the same example as last week’s post to simplify our code a bit.

Polymorphism can be complex but we’ll keep it simple.


class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age


    def speak(self):
        return f"{self.name} is an animal."

class Dog(Animal):
    #Method overriding - we're redefining the method
    def speak(self):
        return f"{self.name} is a dog."
        #inherited the self.name from the Animal class

class Cat(Animal):
    #Method overriding - we're redefining the method
    def speak(self):
        return f"{self.name} is a cat." 
        #inherited the self.name from the Animal class
  

# Usage
animal = Animal("goofy", 5)
dog = Dog("Buddy", 10)
cat = Cat("Whiskers", 5)
print(animal.speak()) # Output: Animal is an animal.
print(dog.speak())  # Output: Buddy is a dog.
print(cat.speak())  # Output: Whiskers is an cat.
class Animal {
    String name;
    int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String speak() {
        return name + " is an animal.";
    }
}


class Dog extends Animal {
    
    public Dog(String name, int age) {
        super(name, age); //Allows us to access parent class info.
    }

    //  Method overriding - we're redefining the method
    public String speak() {
        return name + " is a dog.";
    }
}

// Subclass/Child class
class Cat extends Animal {
    
    public Cat(String name, int age) {
        super(name, age); //Allows us to access parent class info.
    }
    // Method overriding - we're redefining the method
    public String speak() {
        return name + " is a cat.";
    }
}

// Usage
public class Main {
    public static void main(String[] args) {
         // Usage
        Animal animal = new Animal("goofy", 5)
        Dog dog = new Dog("Buddy", 10);
        Cat cat = new Cat("Whiskers", 5);
        System.out.println(animal.speak());
        // Output: goofy is an animal.
        System.out.println(cat.speak());
        // Output: Whiskers is a cat.
        System.out.println(dog.speak()); 
        // Output: Buddy is an animal.
        System.out.println(cat.speak());     
        // Output: Whiskers is an animal.

    }
}
#include <iostream>
#include <string>

using namespace std;

// Base class
class Animal {
  public:
    string name;
    int age;

    Animal(string name, int age) : name(name), age(age) {}

    void speak() {
      cout << name << " is an animal.\n";
    }
};

// Derived class
class Dog : public Animal {
  public:
    Dog(string name, int age) : Animal(name, age) {}

    void speak() {
      cout << name << " is a dog.\n";
    }
};

// Derived class
class Cat : public Animal {
  public:
    Cat(string name, int age) : Animal(name, age) {}

    void speak() {
      cout << name << " is a cat.\n";
    }
};

int main() {
    Animal animal("Goofy", 5);
    Dog dog("Buddy", 10);
    Cat cat("Whiskers", 5);

    animal.speak(); // Output: Goofy is an animal
    dog.speak();    // Output: Buddy is a dog
    cat.speak();    // Output: Whiskers is a cat

    return 0;
}

Even though dog and cat are derived from the animal class, their speak methods behave different.

There’s also different types of polymorphism and here’s an easy way to tell which one is happening:

  1. Compile time polymorphism - method overloading

  2. Runtime polymorphism - method overriding

Best Practices:

  • Design clear and concise interfaces

  • Use method overriding carefully.

  • Leverage polymorphism for flexible code design

  • Combine with other OOP principles for robust systems

Common Pitfalls:

  • Overuse leading to unnecessarily complex hierarchies

  • Confusion between overloading and overriding

  • Performance overhead in some languages

Real-World Analogy: Think of a universal remote control. It can operate various devices (TV, DVD player, sound system) through a common interface, despite each device having different underlying operations.

Remember: Polymorphism is about providing a single interface to entities of different types. It's a powerful tool for creating flexible and scalable code.

Quick Tip: When designing systems, think about what behaviors different objects might share. These common behaviors are excellent candidates for polymorphic interfaces.

Grok-2 Beta Release (6 minute read)

We announce our new Grok-2 and Grok-2 mini models.

Everything Google announced at the Pixel 9 launch event (5 minute read)

Pixels aplenty.

Waymo is developing a roomier robotaxi with less-expensive tech (3 minute read)

Alphabet-owned Waymo has revealed details about its newest "generation 6" self-driving technology as it looks to scale its robotaxi operations in the U.S.

Prompt caching with Claude (2 minute read)

Prompt caching, which enables developers to cache frequently used context between API calls, is now available on the Anthropic API.

Knock | Notifications infrastructure for developers

Knock is flexible, reliable notifications infrastructure that's built to scale with you.

Good Refactoring vs Bad Refactoring (12 minute read)

Refactoring can make your code way better - or way worse. Here's how to avoid messing up your codebase when you refactor code.

Dependency injection in React (8 minute read)

How to Manage Dependencies in Your React App for Cleaner and Easier to Maintain Code.

How Hackers Exploit Vulnerabilities with Nmap and Searchsploit (3 minute read)

Thank you to everyone who submitted last week 😃

coasterkolja, FragileBranch, Drodriguezponce1, ddat828, ravener, sloprope (sent 2 solutions I respect that), VSparl, sarolta-nemeth, RelyingEarth87, Neko0kami, DevonKirby, and the last 2:

Nearest Vowel

Given a letter, created a function which returns the nearest vowel to the letter. If two vowels are equal distance to the given letter, return the earlier vowel.

Examples

nearest_vowel("b") 
output = "a" # closest vowel is a
nearest_vowel("s") 
output = "u" # closest vowel is u
nearest_vowel("c")
output = "a" # closest vowel is a
nearest_vowel("i")
output = "i" # i is a vowel, so return itself

Notes

  • All letters will be given in lowercase.

  • There will be no alphabet wrapping involved, meaning the closest vowel to "z" should return "u", not "a".

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • or if you’re on the web version leave a comment!

Consistent uploads???

Check out the new video I posted if you haven’t already 😄

Another video is being cooked up

Yep I’m working on the next video hoping to post it this week/early next week.

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

See you all next week.

Reply

Avatar

or to participate

Keep Reading

envelope-simple

Join 50k+ developers and become a better programmer and stay up to date in just 5 minutes.

© 2026 Sloth Bytes.
Report abusePrivacy policyTerms of use
beehiivPowered by beehiiv