Kotlin Inheritance & Polymorphism
Kotlin Inheritance & Polymorphism (Deep Explanation)
Kotlin supports inheritance and polymorphism with strict rules that make code safe, explicit, and less error-prone than Java.
PART 1: INHERITANCE IN KOTLIN
1. What is Inheritance?
Inheritance allows a child class to reuse properties and functions of a parent class.
2. open Keyword (Very Important)
In Kotlin:
-
Classes are final by default
-
Functions are final by default
You must use open to allow inheritance.
3. Creating a Child Class
4. Overriding Functions
Parent function must be open, child must use override.
5. Overriding Properties
Rules:
-
val→ can be overridden byvalorvar -
var→ can be overridden only byvar
6. Calling Parent Implementation (super)
7. Primary Constructor in Inheritance
8. Preventing Override (final)
Child cannot override breathe().
PART 2: POLYMORPHISM IN KOTLIN
9. What is Polymorphism?
Polymorphism means:
One reference, different behavior
10. Runtime Polymorphism (Dynamic Dispatch)
Decision happens at runtime.
11. Compile-Time Polymorphism (Overloading)
12. Abstract Classes (Inheritance + Polymorphism)
13. Interfaces & Polymorphism
14. Multiple Inheritance (Interfaces Only)
Kotlin does NOT allow multiple class inheritance
But supports multiple interfaces.
15. Smart Cast & Polymorphism
16. Sealed Classes (Restricted Polymorphism)
Used with when:
17. Real-World Example
Summary (Key Rules)
✔ open required for inheritance
✔ override is mandatory
✔ Polymorphism works via parent references
✔ Use abstract & sealed for controlled hierarchies
✔ Interfaces support multiple inheritance
