0
0
KotlinConceptBeginner · 3 min read

What is Inheritance in Kotlin: Explanation and Example

In Kotlin, inheritance allows a class to inherit properties and functions from another class, called the superclass. This helps reuse code and create a hierarchy where child classes extend or customize the behavior of parent classes.
⚙️

How It Works

Inheritance in Kotlin works like a family tree where a child inherits traits from their parents. Here, a child class (also called a subclass) gets the properties and functions of a parent class (superclass). This means you don't have to write the same code again; the child class can use or change what it inherits.

Think of it like a car blueprint: a basic car class has common features like wheels and engine. A sports car class can inherit these features and add its own special parts like a spoiler. This makes your code simpler and organized.

In Kotlin, classes are final by default, so you must mark a class with open to allow inheritance. The child class uses a colon : to extend the parent class.

💻

Example

This example shows a Vehicle class with a function, and a Car class that inherits from Vehicle and adds its own function.

kotlin
open class Vehicle(val brand: String) {
    fun drive() {
        println("Driving the $brand vehicle")
    }
}

class Car(brand: String, val model: String) : Vehicle(brand) {
    fun showModel() {
        println("This car model is $model")
    }
}

fun main() {
    val myCar = Car("Toyota", "Corolla")
    myCar.drive()       // Inherited from Vehicle
    myCar.showModel()   // Defined in Car
}
Output
Driving the Toyota vehicle This car model is Corolla
🎯

When to Use

Use inheritance when you have classes that share common features but also have their own unique parts. It helps avoid repeating code and makes your program easier to maintain.

For example, in a game, you might have a general Character class with health and movement, and then specific classes like Wizard or Warrior that inherit from it but add special abilities.

Inheritance is useful for creating clear relationships between objects and organizing code logically.

Key Points

  • Kotlin classes are final by default; use open to allow inheritance.
  • Child classes use : to extend a parent class.
  • Inheritance promotes code reuse and logical structure.
  • Child classes can add or override functions and properties.

Key Takeaways

Inheritance lets a class reuse code from another class by extending it.
Mark a class with open to allow other classes to inherit from it in Kotlin.
Use inheritance to organize related classes and avoid repeating code.
Child classes can add new features or change inherited behavior.
Inheritance helps build clear and maintainable code structures.