Polymorphism in Kotlin
Polymorphism is a core concept of object-oriented programming that allows objects to be treated as instances of their parent class rather than their actual class.
It enables one interface to be used for multiple forms (types) of objects.
1. Why Polymorphism Matters
- Code Reusability: You can write generic code that works with different types of objects.
- Extensibility: Easily add new classes with minimal changes to existing code.
- Runtime Flexibility: The program can decide at runtime which method implementation to execute.
2. Types of Polymorphism in Kotlin
Polymorphism in Kotlin can be broadly classified into:
- Compile-time (Static) Polymorphism: Method overloading — multiple methods with the same name but different parameters.
- Runtime (Dynamic) Polymorphism: Method overriding — subclass provides its own implementation for a method defined in the parent class.
3. Compile-time Polymorphism (Method Overloading)
class Calculator {
fun add(a: Int, b: Int) = a + b
fun add(a: Int, b: Int, c: Int) = a + b + c
}
fun main() {
val calc = Calculator()
println(calc.add(2, 3)) // Output: 5
println(calc.add(2, 3, 4)) // Output: 9
}
4. Runtime Polymorphism (Method Overriding)
open class Animal {
open fun sound() {
println("Some generic sound")
}
}
class Dog : Animal() {
override fun sound() {
println("Bark")
}
}
class Cat : Animal() {
override fun sound() {
println("Meow")
}
}
fun main() {
val animals: List = listOf(Dog(), Cat())
for (animal in animals) {
animal.sound() // Runtime decides which sound() to call
}
}
Output:
Bark
Meow
5. Polymorphism with Interfaces
interface Flyer {
fun fly()
}
class Bird : Flyer {
override fun fly() = println("Bird is flying")
}
class Plane : Flyer {
override fun fly() = println("Plane is flying")
}
fun main() {
val flyers: List = listOf(Bird(), Plane())
flyers.forEach { it.fly() }
}
Output:
Bird is flying
Plane is flying
6. Technical Interview Questions
- What is polymorphism?
The ability of an object to take multiple forms, allowing a single interface to represent different underlying forms (classes).
- What are the types of polymorphism in Kotlin?
Compile-time (method overloading) and runtime (method overriding).
- How does runtime polymorphism work?
Through method overriding — the actual method executed is determined at runtime based on the object type.
- Can interfaces be used for polymorphism?
Yes, multiple classes implementing the same interface can be treated polymorphically.
7. Key Takeaways
- Polymorphism enables flexibility and code reuse.
- Compile-time polymorphism is achieved with method overloading.
- Runtime polymorphism is achieved with method overriding and interface implementations.
- It allows a single variable or interface to refer to objects of multiple types safely.