Introduction

Greetings! Today, we're going to demystify the crucial terms of Object-oriented programming (OOP): Inheritance and Polymorphism. These concepts form the backbone of efficient OOP. Our journey will unfold as follows: we'll start with an intuitive grasp of Inheritance and its implementation in Kotlin, and then we'll delve into Polymorphism, with a special focus on method overriding.

Understanding Inheritance

Inheritance is akin to repurposing an old blueprint to create something new. In OOP, it allows one class to inherit features (properties and functions) from another.

In Kotlin, we have the Parent Class (also known as Superclass), which provides features, and the Child Class (or Subclass), which receives these features. When implementing, we use the open keyword for the Parent Class (to allow inheritance), and the : symbol for the Child class indicates which Parent class the features are coming from.

Kotlin
// Defining an 'Animal' class (Parent Class). Marking it as 'open' allows other classes to inherit from it.
open class Animal {
    fun eat() {
        println("This animal eats food.") // Prints: "This animal eats food."
    }
}

// 'Cat' class inherits from 'Animal' (Child Class)
class Cat : Animal() {
    // Inherits all features from 'Animal'
}

val myCat = Cat()
myCat.eat() // Prints: "This animal eats food."
Handling Constructors in Inheritance
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal