πŸ’» Programming

Polymorphism

Polymorphism

A core OOP principle of performing different behaviors through the same interface. It increases code flexibility and extensibility and is the basis of the Strategy pattern and dependency injection.

πŸ“– Detailed Explanation

Polymorphism, which means "many forms" in Greek, is one of the four core principles of Object-Oriented Programming (OOP). It allows objects of different types to behave in their own ways through the same interface or method signature. For example, when the draw() method is called, a Circle draws a circle and a Rectangle draws a rectangle; the calling code is the same, but the actual behavior differs depending on the object's type.

Polymorphism is broadly classified into three kinds. Subtype Polymorphism is treating a child class object as its parent class type through inheritance, and it is the most common form. Parametric Polymorphism is parameterizing types through Generics, and a collection that can hold any type, such as List<T>, is a representative example. Ad-hoc Polymorphism is when methods with the same name accept different parameters through method overloading.

Overriding and Overloading are representative ways of implementing polymorphism. Overriding is when a child class redefines a method of its parent class, and which method is called is determined at runtime (dynamic binding). Overloading, on the other hand, is defining methods with the same name in the same class with different parameters only, and the method to call is determined at compile time (static binding). Python does not support overloading directly and achieves a similar effect with default parameter values or *args.

In practice, polymorphism is at the core of the Strategy Pattern and Dependency Injection. The Strategy Pattern defines an algorithm as an Interface and allows the implementation to be swapped at runtime. Dependency Injection makes code depend on an Interface rather than a concrete class, so it can be easily replaced with a Mock object during testing. Modern frameworks such as the Spring Framework, React's Context API, and Python's abstract classes actively use polymorphism to create structures that are extensible and easy to test.

πŸ’» Code Example

Java - Subtype Polymorphism and the Strategy Pattern
// 1. μΈν„°νŽ˜μ΄μŠ€ μ •μ˜ (λ‹€ν˜•μ„±μ˜ 기반)
interface PaymentStrategy {
    void pay(int amount);
}

// 2. λ‹€μ–‘ν•œ κ΅¬ν˜„μ²΄ (같은 μΈν„°νŽ˜μ΄μŠ€, λ‹€λ₯Έ λ™μž‘)
class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;

    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(int amount) {
        System.out.println("μΉ΄λ“œ " + cardNumber + "둜 " + amount + "원 결제");
    }
}

class KakaoPayPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("카카였페이둜 " + amount + "원 결제");
    }
}

// 3. λ‹€ν˜•μ„± ν™œμš© (ꡬ체 ν΄λž˜μŠ€κ°€ μ•„λ‹Œ μΈν„°νŽ˜μ΄μŠ€μ— 의쑴)
class ShoppingCart {
    private PaymentStrategy paymentStrategy;  // μΈν„°νŽ˜μ΄μŠ€ νƒ€μž…

    // μ˜μ‘΄μ„± μ£Όμž… (λŸ°νƒ€μž„μ— κ΅¬ν˜„μ²΄ ꡐ체 κ°€λŠ₯)
    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.paymentStrategy = strategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);  // μ–΄λ–€ κ΅¬ν˜„μ²΄λ“  λ™μΌν•˜κ²Œ 호좜
    }
}

// μ‚¬μš© μ˜ˆμ‹œ
ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment("1234-5678"));
cart.checkout(50000);  // μΉ΄λ“œ 결제

cart.setPaymentStrategy(new KakaoPayPayment());
cart.checkout(30000);  // 카카였페이 결제
Python - Duck Typing and Abstract Classes
from abc import ABC, abstractmethod

# 1. 좔상 클래슀 μ •μ˜
class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        pass

    @abstractmethod
    def draw(self) -> str:
        pass

# 2. ꡬ체 ν΄λž˜μŠ€λ“€ (같은 λ©”μ„œλ“œ, λ‹€λ₯Έ λ™μž‘)
class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

    def draw(self) -> str:
        return f"λ°˜μ§€λ¦„ {self.radius}인 원을 κ·Έλ¦½λ‹ˆλ‹€"

class Rectangle(Shape):
    def __init__(self, width: float, height: float):
        self.width = width
        self.height = height

    def area(self) -> float:
        return self.width * self.height

    def draw(self) -> str:
        return f"{self.width}x{self.height} μ‚¬κ°ν˜•μ„ κ·Έλ¦½λ‹ˆλ‹€"

# 3. λ‹€ν˜•μ„± ν™œμš© (νƒ€μž…μ— 관계없이 λ™μΌν•œ λ°©μ‹μœΌλ‘œ 처리)
def print_shape_info(shape: Shape):
    """μ–΄λ–€ Shapeλ“  λ™μΌν•˜κ²Œ 처리 κ°€λŠ₯"""
    print(f"면적: {shape.area():.2f}")
    print(shape.draw())

# 4. Duck Typing (Python의 νŠΉμ§•)
class Triangle:  # Shapeλ₯Ό μƒμ†ν•˜μ§€ μ•ŠμŒ
    def area(self) -> float:
        return 10.0

    def draw(self) -> str:
        return "μ‚Όκ°ν˜•μ„ κ·Έλ¦½λ‹ˆλ‹€"

# Duck Typing: "였리처럼 κ±·κ³  였리처럼 울면, 그것은 μ˜€λ¦¬λ‹€"
shapes = [Circle(5), Rectangle(4, 6), Triangle()]
for shape in shapes:
    print_shape_info(shape)  # Triangle도 λ™μž‘ν•¨!

πŸ—£ Practical Conversation Example

πŸŽ“ Technical Interview: Explaining the Types of Polymorphism
πŸ‘€
Interviewer
Please explain the types of polymorphism. Could you also tell me the difference between subtype polymorphism and parametric polymorphism?
πŸ‘©
Candidate
Subtype polymorphism is implemented through inheritance relationships. Since a child class object can be handled as its parent class type, it is used like Animal animal = new Dog();. The method is called according to the actual object type at runtime.
πŸ‘©
Candidate
Parametric polymorphism is Generics, which take types as parameters. You can create containers that can hold any type, like List<String> or Map<K, V>. You can write reusable code while maintaining type safety.
πŸ‘€
Interviewer
Then what is the difference in binding time between overloading and overriding?
πŸ‘©
Candidate
Overloading is static binding, which is determined at compile time. When a method is called, the compiler decides which method to call based on the types and number of parameters. Overriding, on the other hand, is dynamic binding, which is determined at runtime. The method to be called is determined by the type of the actual object. This is implemented through the virtual method table (vtable).

πŸ” Code Review: Using Polymorphism
πŸ‘¨β€πŸ’»
Senior Developer (Reviewer)
The if (type == "email") sendEmail() else if (type == "sms") sendSMS() pattern is repeated in this code. Every time a new notification channel is added, all of these conditionals have to be modified, so it seems like it will be hard to maintain.
πŸ‘©β€πŸ’»
Junior Developer
Ah, so I could create a NotificationChannel Interface and define a send(message) method, and have the EmailChannel and SMSChannel classes implement it. Then the calling side would just need to call channel.send(message), right?
πŸ‘¨β€πŸ’»
Senior Developer (Reviewer)
Exactly! That's the way to follow the OCP (Open-Closed Principle). When a new channel is added, you just add a new class without modifying existing code. And if you combine it with the Factory Pattern, you can also cleanly separate the channel creation logic.

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠ Cautions

🚨 Practical Cautions on Polymorphism
  • Follow the LSP (Liskov Substitution Principle): A child class must be able to fully replace its parent class. If Square, which inherits from Rectangle, changes width and height at the same time, it violates the LSP. Consider Composition over inheritance.
  • Use polymorphism instead of type checks: If there is a lot of code that checks types with instanceof or typeof and branches accordingly, it is time to refactor with polymorphism. Solve it with method overriding rather than conditionals.
  • Interface Segregation Principle (ISP): Several small, specific Interfaces are better than one huge Interface. Design so that clients do not depend on methods they do not use.
  • Consistency of abstraction level: Classes in the same layer should maintain a similar level of abstraction. sendEmail() and updateDatabaseAndLogAndNotify() must not be in the same Interface.
  • Avoid excessive inheritance hierarchies: Inheritance hierarchies of three or more levels increase complexity. Prefer Interfaces and Composition over inheritance. Use inheritance only when the "is-a" relationship is clear.

πŸ”— Related Terms

πŸ“š Learn More