Object-Oriented Programming in Kotlin: Classes and Inheritance

February 10, 2024

This post explores the object-oriented programming capabilities of Kotlin, focusing on classes, objects, inheritance, and polymorphism. You will learn how to create and use classes in Kotlin, as well as leverage inheritance to build robust and maintainable code.

Classes in Kotlin

In Kotlin, classes are defined using the class keyword. Here’s an example of a simple class:

class Person {
   var name: String = ""
   var age: Int = 0
}

In this example, we’ve created a Person class with name and age properties. You can create an instance of this class using the following syntax:

val person = Person()
person.name = "John"
person.age = 30

Inheritance in Kotlin

Kotlin supports single inheritance, meaning a class can inherit from only one superclass. To inherit from a class, use the : symbol followed by the superclass name. Here’s an example:

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

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

In this example, the Circle class inherits from the Shape class and overrides the draw method.

Polymorphism in Kotlin

Kotlin supports polymorphism, allowing you to treat objects of derived classes as objects of their base class. Here’s an example:

fun drawShape(shape: Shape) {
   shape.draw()
}

val shape: Shape = Circle()
drawShape(shape)

In this example, the drawShape function accepts a Shape object, and we pass a Circle object to it.