Polymorphism in Kotlin : Start with a Simple Example

Home » Kotlin » Polymorphism in Kotlin : Start with a Simple Example

Polymorphism is a key concept in object-oriented programming that enables the same method or function to behave differently based on the object’s type at runtime. In this Kotlin tutorial, let’s start with polymorphism in Kotlin.

Polymorphism in Kotlin : Start with a Simple Example

The Idea of Polymorphism in Kotlin

Within a class, a singleton object, a companion object, or an interface, it is possible to define multiple functions that share the same name but accept different parameters. While this may seem straightforward, this concept is referred to as polymorphism in object-oriented theory.

When multiple functions share the same name, Kotlin determines the appropriate function to use based on the provided parameters.

Let’s look at an example:

Consider a class called ‘Calculator‘ with several add() functions allowing for an Int parameter a, and String parameter b. Open the Kotlin Playground and write the following program.

fun main()
{
    val obj=Calculator()
    println(obj.add(4))
    println(obj.add("SD Card | "))
}
class Calculator {

    fun add(a:Int): Int
    {
        return a+a // sum
    }
    fun add(b:String): String
    {
        return b+b // concatenation
    }
}

If you now call obj.add() with some argument (eg: 8 or ‘SD Card |’), Kotlin takes the argument’s type to find out which of the functions to call.

Output

8
SD Card | SD Card | 

In Kotlin, you create a base class (also known as a superclass) with common properties and methods. Then, you can create one or more subclasses that inherit from the base class, inheriting its characteristics while adding their unique features.

To achieve polymorphism, you override methods from the base class in the subclasses. This allows each subclass to provide its own implementation of a method while maintaining a consistent interface.

Method overriding is a crucial aspect of polymorphism in Kotlin. When a method in a subclass has the same name, return type, and parameters as a method in the base class, it is said to override the base class method.

Kotlin’s Polymorphism Example

Let’s create a simple Kotlin program that demonstrates polymorphism.


// 1
open class Shape {
    open fun calculateArea(): Double {
        return 0.0
    }
}

// 2
class Circle(private val radius: Double) : Shape() {
    override fun calculateArea(): Double {
        return Math.PI * radius * radius
    }
}

class Rectangle(private val width: Double, private val height: Double) : Shape() {
    override fun calculateArea(): Double {
        return width * height
    }
}

class Triangle(private val base: Double, private val height: Double) : Shape() {
    override fun calculateArea(): Double {
        return 0.5 * base * height
    }
}

fun main() {
    // 3
    val circle = Circle(6.0)
    val rectangle = Rectangle(5.0, 5.0)
    val triangle = Triangle(5.0, 7.0)

    // 4
    val shapes = listOf(circle, rectangle, triangle)

    for (shape in shapes) {
        println("Area: ${shape.calculateArea()}")
    }
}

Step 1: Define a base class ‘Shape’

Step 2: Create subclasses that inherit from ‘Shape’

Step 3: Create instances of different shapes.

Step 4: Calculate and display their areas using polymorphism

Result

Area: 113.09733552923255
Area: 25.0
Area: 17.5

When you run this program, it will calculate and display the areas of the circle, rectangle, and triangle, showing how polymorphism allows you to work with different types of shapes in a uniform way. In this tutorial, we’ve covered the basics of polymorphism in Kotlin.

You may also like...