OOP FundamentalsPolymorphismMedium⏱️ ~3 min

Polymorphism Structure: Types and Mechanisms

Two Types of Polymorphism

Compile-Time Polymorphism (Static): Method overloading where multiple methods share the same name but differ in parameters. The compiler determines which method to call based on the argument types. This is less relevant to LLD design decisions.

Runtime Polymorphism (Dynamic): Method overriding where a subclass provides a specific implementation of a method declared in its parent. The actual method executed is determined at runtime based on the object's actual type, not the reference type.

Class Diagram Structure

Vehicle
- registrationNumber: String
+ calculateParkingFee(hours): Money
+ getVehicleType(): String
Car
+ calculateParkingFee(hours): Money
+ getVehicleType(): String
Motorcycle
+ calculateParkingFee(hours): Money
+ getVehicleType(): String
Truck
+ calculateParkingFee(hours): Money
+ getVehicleType(): String

Key Mechanism: Dynamic Dispatch

When you call vehicle.calculateParkingFee(hours), the actual method executed depends on whether vehicle references a Car, Motorcycle, or Truck object at runtime. The reference type is Vehicle, but the object type determines behavior.

Vehicle vehicle = new Car()
Money fee = vehicle.calculateParkingFee(2) // Calls Car's implementation

This enables the Liskov Substitution Principle (LSP): subtypes must be substitutable for their base types without altering program correctness.

Interview Tip: Interviewers often ask how polymorphism enables extensibility. Show that adding a new Bus class requires no changes to existing code that processes vehicles.
💡 Key Takeaways
Runtime polymorphism uses method overriding with inheritance or interface implementation
Dynamic dispatch determines which method to execute based on the actual object type at runtime
Parent reference can hold child objects, enabling flexible and extensible designs
Supports Liskov Substitution Principle: subtypes are interchangeable with their base types
📌 Examples
1Vehicle hierarchy: Car, Motorcycle, Truck all override calculateParkingFee()
2Shape hierarchy: Circle, Rectangle, Triangle all override calculateArea()
← Back to Polymorphism Overview
Polymorphism Structure: Types and Mechanisms | Polymorphism - System Overflow