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:
- What Inheritance Is
- How to Implement Inheritance in Kotlin
- 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:
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:
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.
