Inheritance in Kotlin: Exploring Properties and Methods
Introduction
Welcome back! In this part of our Kotlin Class Basics Revision, we dive into inheritance, a fundamental concept in object-oriented programming (OOP) with Kotlin. Inheritance allows us to share code across classes, enhancing code organization and efficiency.
In this lesson, we'll explore attribute and method inheritance in Kotlin through practical examples. Our lesson's blueprint includes defining inheritance, examining attribute inheritance, exploring method inheritance, and understanding how to use the super keyword in Kotlin. Let’s dive in!
Defining Inheritance
Inheritance involves creating a child class that inherits properties and functions from a parent class. In Kotlin, whenever classes share common properties or functions, inheritance becomes a relevant tool.
Here's an example featuring a parent class named Vehicle and a child class named Car:
Kotlin supports inheritance through classes, and single inheritance is our focus here, where one parent class serves one child class.
Attribute Inheritance
Attribute inheritance allows a child class to inherit the properties of a parent class.
Consider this example featuring a parent class named Artist, and a child class named Musician:
The Musician class inherits the name property from the Artist class while having its own unique property, instrument.
Method Inheritance
Similar to properties, method inheritance allows a child class to inherit the functions of a parent class.
In the example below, the Car class can invoke the start function from the Vehicle class:
