How to Implement Inheritance In Kotlin?

10 minutes read

In Kotlin, inheritance can be implemented using the "class" keyword followed by the class name and a colon (:), specifying the superclass. The properties and functions of the superclass can then be accessed and overridden in the subclass using the "override" keyword.


To implement inheritance in Kotlin:

  1. Define the superclass: Use the "open" keyword before the class declaration to allow it to be inherited. Declare properties and functions that are common to all subclasses.


Example:

1
2
3
4
5
6
open class Vehicle {
    var brand: String = ""
    open fun accelerate() {
        println("Accelerating...")
    }
}


  1. Declare the subclass: Use the "class" keyword followed by the class name and a colon (:), specifying the superclass. Optional: declare its own properties and functions.


Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Car : Vehicle() {
    fun startEngine() {
        println("Engine started.")
    }
    
    override fun accelerate() {
        super.accelerate()
        println("Speeding up...")
    }
}


  1. Use the subclass: Create an instance of the subclass using the "new" keyword followed by the class name and parentheses. Access properties and functions of both the subclass and superclass.


Example:

1
2
3
4
5
6
fun main() {
    val car = Car()
    car.brand = "Toyota"
    car.startEngine()
    car.accelerate()
}


This is a basic example of implementing inheritance in Kotlin. It allows subclasses to inherit properties and functions from a superclass, while also providing the ability to override or extend them as needed.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.8 out of 5

Kotlin Cookbook: A Problem-Focused Approach

4
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.7 out of 5

Head First Kotlin: A Brain-Friendly Guide

5
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.6 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

6
Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

Rating is 4.5 out of 5

Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

7
Java to Kotlin: A Refactoring Guidebook

Rating is 4.4 out of 5

Java to Kotlin: A Refactoring Guidebook

8
Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing

Rating is 4.3 out of 5

Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing


How to create an abstract class in Kotlin?

To create an abstract class in Kotlin, you can follow these steps:

  1. Open your Kotlin project in an IDE such as IntelliJ IDEA or Android Studio.
  2. Create a new Kotlin file or open an existing one where you want to define your abstract class.
  3. Use the abstract keyword before the class keyword to define the abstract class.
  4. Provide a name for the abstract class, ensuring to follow the Kotlin naming conventions.
  5. Optionally, you can define properties, functions, and constructors inside the abstract class.


Here's an example of how you can create an abstract class in Kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
abstract class Animal(val name: String) {

    abstract fun makeSound()

    fun sleep() {
        println("$name is sleeping")
    }
}

class Dog(name: String) : Animal(name) {

    override fun makeSound() {
        println("$name is barking")
    }
}

class Cat(name: String) : Animal(name) {

    override fun makeSound() {
        println("$name is meowing")
    }
}

fun main() {
    val dog = Dog("Buddy")
    dog.makeSound() // Output: Buddy is barking
    dog.sleep() // Output: Buddy is sleeping

    val cat = Cat("Whiskers")
    cat.makeSound() // Output: Whiskers is meowing
    cat.sleep() // Output: Whiskers is sleeping
}


In this example, the Animal class is defined as an abstract class with an abstract function makeSound() and a non-abstract function sleep(). The Dog and Cat classes inherit from the abstract class Animal and override the makeSound() function. Finally, the main() function demonstrates the usage of these classes by creating instances and calling their methods.


How to achieve polymorphism using inheritance in Kotlin?

To achieve polymorphism using inheritance in Kotlin, you need to follow these steps:

  1. Create a parent class: Start by defining a parent class. This class will have common properties and methods that will be inherited by the child classes.
1
2
3
4
5
open class Animal {
    open fun makeSound() {
        println("The animal makes a sound")
    }
}


  1. Create child classes: Create multiple child classes that inherit from the parent class. These classes can have their own unique properties and methods, while also inheriting the common properties and methods from the parent class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Dog : Animal() {
    override fun makeSound() {
        println("The dog barks")
    }
}

class Cat : Animal() {
    override fun makeSound() {
        println("The cat meows")
    }
}


  1. Use polymorphism: Now, you can create objects of the child classes and use them interchangeably with the parent class.
1
2
3
4
5
6
7
fun main() {
    val animals = arrayOf(Animal(), Dog(), Cat())

    for (animal in animals) {
        animal.makeSound()
    }
}


In the example above, an array of animals is created, including objects of the Animal, Dog, and Cat classes. The makeSound() method is called on each animal, resulting in the appropriate sound for each specific animal being printed. This demonstrates the concept of polymorphism, where different objects can be treated as if they belong to the same type (in this case, the Animal type) and exhibit different behaviors based on their actual type.


What is a subclass in inheritance?

In inheritance, a subclass (or derived class) is a class that inherits properties and behaviors (methods) from another class called the superclass (or base class). It is created by extending the superclass and can add additional features or functionalities to the existing ones inherited from the superclass. The subclass inherits all the non-private members (fields and methods) of the superclass, allowing for code reuse and promoting the principle of code modularity and abstraction.


What is the keyword used for inheritance in Kotlin?

The keyword used for inheritance in Kotlin is "open".


How to implement multiple inheritance in Kotlin?

In Kotlin, multiple inheritance can be achieved using interfaces. Here's how you can implement multiple inheritance in Kotlin:

  1. Create interfaces: Define multiple interfaces with the required methods and properties.
1
2
3
4
5
6
7
interface InterfaceA {
    fun methodA()
}

interface InterfaceB {
    fun methodB()
}


  1. Create a class: Implement the interfaces in a class using the : symbol to denote inheritance from each interface.
1
2
3
4
5
6
7
8
9
class MyClass : InterfaceA, InterfaceB {
    override fun methodA() {
        // Implementation for methodA
    }
    
    override fun methodB() {
        // Implementation for methodB
    }
}


  1. Use the class: You can now create an instance of the class and call the methods defined in both interfaces.
1
2
3
val obj = MyClass()
obj.methodA() // Call methodA()
obj.methodB() // Call methodB()


By implementing multiple interfaces in a class, you can achieve the functionality of multiple inheritance in Kotlin. Remember that if two or more interfaces have methods with the same name, you need to provide an implementation for each method in the class that implements them.

Twitter LinkedIn Telegram Whatsapp

Related Posts:

Working with the Kotlin Collections API allows you to efficiently manage and manipulate collections of data in your Kotlin code. Kotlin provides a rich set of built-in functions and operators that make it easy to perform common operations on lists, sets, and m...
To create a Kotlin class, follow these steps:Start by opening your Kotlin project in an integrated development environment (IDE) like IntelliJ IDEA or Android Studio. Create a new Kotlin file by right-clicking on the desired package or directory within your pr...
Serializing and deserializing JSON in Kotlin involves converting JSON data into Kotlin objects and vice versa. Here's a step-by-step explanation of how to achieve this:Add the JSON serialization and deserialization library: Start by adding the necessary li...