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.
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.
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.
// 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); // μΉ΄μΉ΄μ€νμ΄ κ²°μ
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λ λμν¨!
Animal animal = new Dog();. The method is called according to the actual object type at runtime.List<String> or Map<K, V>. You can write reusable code while maintaining type safety.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.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?Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Square, which inherits from Rectangle, changes width and height at the same time, it violates the LSP. Consider Composition over inheritance.instanceof or typeof and branches accordingly, it is time to refactor with polymorphism. Solve it with method overriding rather than conditionals.sendEmail() and updateDatabaseAndLogAndNotify() must not be in the same Interface.