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.
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.
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.
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.
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 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.
Kotlin designers made classes final by default to encourage composition over inheritance. This prevents misuse of inheritance and encourages better design practices.
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.
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.
open class Shape {
open fun draw() {
println("Drawing a shape")
}
}
class Circle : Shape() {
override fun draw() {
println("Drawing a circle")
}
}
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.
open class Person {
open fun display() {
println("Person details")
}
}
class Student : Person() {
override fun display() {
super.display()
println("Student details")
}
}
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.
open class Employee(val name: String)
class Manager(name: String) : Employee(name)
The Manager class passes the name parameter to the Employee class constructor.
open class Account {
constructor(id: Int) {
println("Account ID: " + id)
}
}
class SavingsAccount : Account {
constructor(id: Int) : super(id)
}
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.
abstract class Bank {
abstract fun interestRate()
fun bankInfo() {
println("Bank information")
}
}
class SBI : Bank() {
override fun interestRate() {
println("Interest rate is 5%")
}
}
Kotlin interfaces support inheritance and can contain abstract methods and default implementations. A class can implement multiple interfaces, supporting multiple inheritance behavior.
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")
}
}
Kotlin does not support multiple inheritance using classes, but it allows multiple inheritance through interfaces. When conflicts occur, Kotlin requires explicit implementation.
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 control access to class members during inheritance. Kotlin supports public, protected, internal, and private visibility.
Using the final keyword prevents inheritance or overriding. This is useful for security and design stability.
open class Logger {
final fun log() {
println("Logging data")
}
}
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.
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.
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.
Copyrights © 2024 letsupdateskills All rights reserved