How to Extend a Class Having Multiple Constructors in Kotlin

Fariba Laiq Feb 02, 2024
How to Extend a Class Having Multiple Constructors in Kotlin

Inheritance is a significant concept in object-oriented programming in which a derived class inherits all the features from its base/superclass and can also have its features.

This article discusses how to extend a class that has multiple constructors. A constructor is a function called at the time of object creation to initialize the class variables.

Extend a Class Having Multiple Constructors in Kotlin

Usually, we cannot inherit multiple primary constructors from the superclass and call any one of them based on the situation. To resolve this issue, we can use secondary constructors.

Although, secondary constructors are not that common in Kotlin. But they are handy when inheriting multiple constructors from the superclass.

Secondary constructors are defined using the keyword constructor. In the following example, the superclass Fruit has two secondary and no primary constructors.

We created a derived class Mango with two secondary constructors and called any of the superclass constructors based on the context. This way, we can inherit multiple constructors from the base class.

Example Code:

public open class Fruit{
    public constructor(message: String, color:String) {
        println("$message $color")
    }
    public constructor(message:String) {
        println("$message")
    }
}

public class Mango: Fruit{
    constructor(message:String, color:String):super(message, color) {
        
    }
    public constructor(message:String):super(message) {
        
    }
}

fun main(args : Array<String>) {
    Mango("I am a mango.")
    Mango("I am a mango", "Yellow One.")
}

Output:

I am a mango.
I am a mango Yellow One.
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Kotlin Class