Kotlin - Inheritance

Kotlin Inheritance – Complete Guide for Object-Oriented Programming

Kotlin Inheritance 

Introduction to Kotlin Inheritance

Kotlin Inheritance is one of the most important pillars of Object-Oriented Programming in Kotlin. Inheritance allows a class to acquire the properties and behaviors of another class, enabling code reuse, better organization, and easier maintenance. Kotlin, as a modern programming language, introduces clear and safe rules for inheritance to avoid common pitfalls found in older languages.

In this detailed guide, you will learn Kotlin Inheritance from basics to advanced concepts. This content is designed for beginners, students, and professionals using Kotlin for Android development, backend development, or general-purpose programming.

What is Inheritance in Kotlin?

Inheritance in Kotlin is a mechanism where one class, called the child class or derived class, inherits the properties and functions of another class, called the parent class or base class. The main purpose of inheritance is code reusability and logical hierarchy creation.

Kotlin follows a strict inheritance model by default. All classes in Kotlin are final by default, which means they cannot be inherited unless explicitly declared as open. This design choice helps prevent unintended inheritance and promotes safer code.

Why Kotlin Uses Explicit Inheritance Rules

Unlike Java, Kotlin enforces explicit inheritance rules. A class must be marked as open to allow inheritance, and its methods must also be marked as open to allow overriding. This approach reduces bugs, improves readability, and ensures developers are aware of inheritance relationships in their codebase.

Base Class and Derived Class in Kotlin

In Kotlin, a base class is the class whose properties and methods are inherited. A derived class is the class that inherits from the base class. The colon symbol is used to indicate inheritance.

Example of Simple Inheritance


open class Animal {
    fun eat() {
        println("Animal is eating")
    }
}

class Dog : Animal() {
    fun bark() {
        println("Dog is barking")
    }
}

In this example, Animal is the base class, and Dog is the derived class. The Dog class can access the eat function from the Animal class.

The open Keyword in Kotlin Inheritance

The open keyword is mandatory if you want a class or function to be inherited or overridden. By default, classes and functions are final, meaning they cannot be extended or modified.

Why Classes Are Final by Default

Kotlin designers made classes final by default to encourage composition over inheritance. This prevents misuse of inheritance and encourages better design practices.

Example Using open Keyword


open class Vehicle {
    open fun start() {
        println("Vehicle is starting")
    }
}

class Car : Vehicle() {
    override fun start() {
        println("Car is starting")
    }
}

Here, both the class and the function are marked as open, allowing the Car class to override the start function.

Overriding Methods in Kotlin

Method overriding allows a child class to provide a specific implementation of a method defined in the parent class. Kotlin requires the override keyword to make overriding explicit.

Rules for Method Overriding

  • The parent method must be open
  • The child method must use the override keyword
  • Method signatures must match

Example of Method Overriding


open class Shape {
    open fun draw() {
        println("Drawing a shape")
    }
}

class Circle : Shape() {
    override fun draw() {
        println("Drawing a circle")
    }
}

Calling Parent Class Functions Using super

The super keyword is used to call methods or access properties of the parent class. It is commonly used when overriding functions and still needing parent behavior.

Example Using super Keyword


open class Person {
    open fun display() {
        println("Person details")
    }
}

class Student : Person() {
    override fun display() {
        super.display()
        println("Student details")
    }
}

Inheritance and Constructors in Kotlin

Kotlin handles inheritance with constructors in a structured way. A derived class must call the constructor of the base class. Primary and secondary constructors follow specific rules during inheritance.

Primary Constructor Inheritance


open class Employee(val name: String)

class Manager(name: String) : Employee(name)

The Manager class passes the name parameter to the Employee class constructor.

Secondary Constructor Inheritance


open class Account {
    constructor(id: Int) {
        println("Account ID: " + id)
    }
}

class SavingsAccount : Account {
    constructor(id: Int) : super(id)
}

Abstract Classes in Kotlin

An abstract class in Kotlin is a class that cannot be instantiated. It is designed to be inherited and may contain abstract methods without implementation.

Features of Abstract Classes

  • Cannot be instantiated
  • Can contain abstract and non-abstract methods
  • Supports inheritance

Example of Abstract Class


abstract class Bank {
    abstract fun interestRate()
    
    fun bankInfo() {
        println("Bank information")
    }
}

class SBI : Bank() {
    override fun interestRate() {
        println("Interest rate is 5%")
    }
}

Interface Inheritance in Kotlin

Kotlin interfaces support inheritance and can contain abstract methods and default implementations. A class can implement multiple interfaces, supporting multiple inheritance behavior.

Example of Interface Inheritance


interface Engine {
    fun startEngine()
}

interface Electric {
    fun charge()
}

class ElectricCar : Engine, Electric {
    override fun startEngine() {
        println("Electric engine started")
    }

    override fun charge() {
        println("Car is charging")
    }
}

Multiple Inheritance and Conflict Resolution

Kotlin does not support multiple inheritance using classes, but it allows multiple inheritance through interfaces. When conflicts occur, Kotlin requires explicit implementation.

Example of Conflict Resolution


interface A {
    fun show() {
        println("Show from A")
    }
}

interface B {
    fun show() {
        println("Show from B")
    }
}

class C : A, B {
    override fun show() {
        println("Show from C")
    }
}

Visibility Modifiers and Inheritance

Visibility modifiers control access to class members during inheritance. Kotlin supports public, protected, internal, and private visibility.

Visibility Rules in Inheritance

  • public members are accessible everywhere
  • protected members are accessible in subclasses
  • private members are not inherited

Final Classes and Functions

Using the final keyword prevents inheritance or overriding. This is useful for security and design stability.

Example of Final Usage


open class Logger {
    final fun log() {
        println("Logging data")
    }
}

Real-World Use Cases of Kotlin Inheritance

Kotlin Inheritance is widely used in Android development, backend services, game development, and enterprise applications. Examples include base activities, repository patterns, UI components, and service layers.

Common Mistakes in Kotlin Inheritance

  • Forgetting the open keyword
  • Overusing inheritance
  • Ignoring visibility rules
  • Creating deep inheritance trees


Kotlin Inheritance is a powerful feature that enables clean, reusable, and maintainable code. By enforcing explicit inheritance rules, Kotlin ensures better design and fewer runtime errors. Understanding inheritance, abstract classes, interfaces, and overriding is essential for mastering Kotlin Object Oriented Programming.

Beginner 5 Hours
Kotlin Inheritance – Complete Guide for Object-Oriented Programming

Kotlin Inheritance 

Introduction to Kotlin Inheritance

Kotlin Inheritance is one of the most important pillars of Object-Oriented Programming in Kotlin. Inheritance allows a class to acquire the properties and behaviors of another class, enabling code reuse, better organization, and easier maintenance. Kotlin, as a modern programming language, introduces clear and safe rules for inheritance to avoid common pitfalls found in older languages.

In this detailed guide, you will learn Kotlin Inheritance from basics to advanced concepts. This content is designed for beginners, students, and professionals using Kotlin for Android development, backend development, or general-purpose programming.

What is Inheritance in Kotlin?

Inheritance in Kotlin is a mechanism where one class, called the child class or derived class, inherits the properties and functions of another class, called the parent class or base class. The main purpose of inheritance is code reusability and logical hierarchy creation.

Kotlin follows a strict inheritance model by default. All classes in Kotlin are final by default, which means they cannot be inherited unless explicitly declared as open. This design choice helps prevent unintended inheritance and promotes safer code.

Why Kotlin Uses Explicit Inheritance Rules

Unlike Java, Kotlin enforces explicit inheritance rules. A class must be marked as open to allow inheritance, and its methods must also be marked as open to allow overriding. This approach reduces bugs, improves readability, and ensures developers are aware of inheritance relationships in their codebase.

Base Class and Derived Class in Kotlin

In Kotlin, a base class is the class whose properties and methods are inherited. A derived class is the class that inherits from the base class. The colon symbol is used to indicate inheritance.

Example of Simple Inheritance

open class Animal { fun eat() { println("Animal is eating") } } class Dog : Animal() { fun bark() { println("Dog is barking") } }

In this example, Animal is the base class, and Dog is the derived class. The Dog class can access the eat function from the Animal class.

The open Keyword in Kotlin Inheritance

The open keyword is mandatory if you want a class or function to be inherited or overridden. By default, classes and functions are final, meaning they cannot be extended or modified.

Why Classes Are Final by Default

Kotlin designers made classes final by default to encourage composition over inheritance. This prevents misuse of inheritance and encourages better design practices.

Example Using open Keyword

open class Vehicle { open fun start() { println("Vehicle is starting") } } class Car : Vehicle() { override fun start() { println("Car is starting") } }

Here, both the class and the function are marked as open, allowing the Car class to override the start function.

Overriding Methods in Kotlin

Method overriding allows a child class to provide a specific implementation of a method defined in the parent class. Kotlin requires the override keyword to make overriding explicit.

Rules for Method Overriding

  • The parent method must be open
  • The child method must use the override keyword
  • Method signatures must match

Example of Method Overriding

open class Shape { open fun draw() { println("Drawing a shape") } } class Circle : Shape() { override fun draw() { println("Drawing a circle") } }

Calling Parent Class Functions Using super

The super keyword is used to call methods or access properties of the parent class. It is commonly used when overriding functions and still needing parent behavior.

Example Using super Keyword

open class Person { open fun display() { println("Person details") } } class Student : Person() { override fun display() { super.display() println("Student details") } }

Inheritance and Constructors in Kotlin

Kotlin handles inheritance with constructors in a structured way. A derived class must call the constructor of the base class. Primary and secondary constructors follow specific rules during inheritance.

Primary Constructor Inheritance

open class Employee(val name: String) class Manager(name: String) : Employee(name)

The Manager class passes the name parameter to the Employee class constructor.

Secondary Constructor Inheritance

open class Account { constructor(id: Int) { println("Account ID: " + id) } } class SavingsAccount : Account { constructor(id: Int) : super(id) }

Abstract Classes in Kotlin

An abstract class in Kotlin is a class that cannot be instantiated. It is designed to be inherited and may contain abstract methods without implementation.

Features of Abstract Classes

  • Cannot be instantiated
  • Can contain abstract and non-abstract methods
  • Supports inheritance

Example of Abstract Class

abstract class Bank { abstract fun interestRate() fun bankInfo() { println("Bank information") } } class SBI : Bank() { override fun interestRate() { println("Interest rate is 5%") } }

Interface Inheritance in Kotlin

Kotlin interfaces support inheritance and can contain abstract methods and default implementations. A class can implement multiple interfaces, supporting multiple inheritance behavior.

Example of Interface Inheritance

interface Engine { fun startEngine() } interface Electric { fun charge() } class ElectricCar : Engine, Electric { override fun startEngine() { println("Electric engine started") } override fun charge() { println("Car is charging") } }

Multiple Inheritance and Conflict Resolution

Kotlin does not support multiple inheritance using classes, but it allows multiple inheritance through interfaces. When conflicts occur, Kotlin requires explicit implementation.

Example of Conflict Resolution

interface A { fun show() { println("Show from A") } } interface B { fun show() { println("Show from B") } } class C : A, B { override fun show() { println("Show from C") } }

Visibility Modifiers and Inheritance

Visibility modifiers control access to class members during inheritance. Kotlin supports public, protected, internal, and private visibility.

Visibility Rules in Inheritance

  • public members are accessible everywhere
  • protected members are accessible in subclasses
  • private members are not inherited

Final Classes and Functions

Using the final keyword prevents inheritance or overriding. This is useful for security and design stability.

Example of Final Usage

open class Logger { final fun log() { println("Logging data") } }

Real-World Use Cases of Kotlin Inheritance

Kotlin Inheritance is widely used in Android development, backend services, game development, and enterprise applications. Examples include base activities, repository patterns, UI components, and service layers.

Common Mistakes in Kotlin Inheritance

  • Forgetting the open keyword
  • Overusing inheritance
  • Ignoring visibility rules
  • Creating deep inheritance trees


Kotlin Inheritance is a powerful feature that enables clean, reusable, and maintainable code. By enforcing explicit inheritance rules, Kotlin ensures better design and fewer runtime errors. Understanding inheritance, abstract classes, interfaces, and overriding is essential for mastering Kotlin Object Oriented Programming.

Related Tutorials

Frequently Asked Questions for Kotlin

Companion objects hold static members, like Java’s static methods, in Kotlin classes.

A concise way to define anonymous functions using { parameters -> body } syntax.

Kotlin prevents null pointer exceptions using nullable (?) and non-null (!!) type syntax.

Inline functions reduce overhead by inserting function code directly at call site.

JetBrains, the makers of IntelliJ IDEA, developed Kotlin and released it in 2011.

Allows non-null variables to be initialized after declaration (used with var only).

val is immutable (read-only), var is mutable (can change value).

Compiler automatically determines variable types, reducing boilerplate code.

A data class automatically provides equals(), hashCode(), toString(), and copy() methods.

A function that takes functions as parameters or returns them.

Kotlin is a modern, statically typed language that runs on the Java Virtual Machine (JVM).

They add new methods to existing classes without modifying their source code.

It allows unpacking data class properties into separate variables.

== checks value equality; === checks reference (memory) equality.


apply is a scope function to configure an object and return it.

A class that restricts subclassing, useful for representing restricted class hierarchies.

Coroutines enable asynchronous programming by suspending and resuming tasks efficiently.

Functions can define default values for parameters, avoiding overloads.

Kotlin offers concise syntax, null safety, and modern features not found in Java.

Kotlin automatically casts variables to appropriate types after type checks.

Use the object keyword to create a singleton.

Calls a method only if the object is non-null.

Yes, Kotlin supports backend development using frameworks like Ktor and Spring Boot.

Data structures like List, Set, and Map, supporting functional operations.

line

Copyrights © 2024 letsupdateskills All rights reserved