Inheritance in Kotlin

Inheritance in Kotlin

Welcome back! Now that you have a solid understanding of classes and objects, it's time to build on that knowledge by exploring inheritance. Consider it a natural progression in our journey into object-oriented programming (OOP).

Inheritance allows you to create a new class based on an existing class. By using inheritance, you can reuse code, add new features, and make your programs easier to manage and understand. Let's dive in and see what it's all about.

What We'll Cover

In this lesson, you'll understand how to use inheritance in Kotlin. We'll cover:

  1. What Inheritance Is
  2. How to Implement Inheritance in Kotlin
  3. Why Inheritance Is Beneficial

You'll also learn about chaining inheritance and how to manage multiple inheritance using interfaces.

What Inheritance Is

Inheritance is a way to establish a relationship between a new class (derived class) and an existing class (base class). The derived class inherits properties and behaviors (methods) from the base class. To better understand this concept, we'll use an example involving a Person class as the base class and a Student class as the derived class. This example will help demonstrate how properties and methods are inherited from the base class and how additional features can be added to the derived class.

Base Class: Person

Let’s start by defining a Person class, which will act as the base class in our example:

Kotlin
// Define the base class Person with name and age attributes
open class Person(private val name: String, private val age: Int) {

    // Display function to show name and age
    fun display() {
        println("Name: $name, Age: $age")
    }
}

In this snippet, the Person class is defined with private properties name and age using a primary constructor. It also includes a display method to print the details. The open keyword allows this class to be inherited.

Derived Class: Student

Now, let’s create a Student class that inherits from the Person class:

Kotlin
// Define the derived class Student, inheriting from Person
class Student(name: String, age: Int, private val major: String) : Person(name, age) {

    // Function to display major of the student
    fun displayMajor() {
        println("Major: $major")
    }
}

In the Student class, we use : to inherit from Person. The Student class reuses the name and age properties from the Person class, and it adds a new property, major. The super call to initialize inherited properties is implicit in Kotlin primary constructors.

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