Kotlin – 12 – Classes and Objects in Kotlin

Classes and objects are fundamental building blocks in Kotlin, providing a structured way to define data and behavior in your code. In this guide, we’ll delve into classes and objects in Kotlin, explaining how to create them, define properties and methods, and utilize them in your programs.

Defining a Class

In Kotlin, a class is a blueprint for creating objects. To define a class, you use the class keyword followed by the class name. Here’s a simple example of a class definition:

class Person {
    // Properties (fields)
    var name: String = ""
    var age: Int = 0
}

In this example, we’ve defined a Person class with two properties: name and age. Properties are essentially variables associated with the class.

Creating Objects

Once you’ve defined a class, you can create objects (instances) of that class. To create an object, you use the class name followed by parentheses. Here’s how you create an instance of the Person class:

val person = Person()

Now, the person variable holds an instance of the Person class.

Accessing Properties

You can access the properties of an object using dot notation. Here’s how you can set and retrieve values for the name and age properties of the person object:

person.name = "Alice"
person.age = 30

println("Name: ${person.name}, Age: ${person.age}")

This code sets the name property to “Alice” and the age property to 30, then prints their values.

Constructors

Kotlin allows you to define one or more constructors for a class. A constructor is a special function that initializes the properties of an object when it’s created. The primary constructor is often defined in the class header, and secondary constructors are declared using the constructor keyword. Here’s an example with both primary and secondary constructors:

class Book(val title: String, val author: String) {
    var pages: Int = 0

    constructor(title: String, author: String, pages: Int) : this(title, author) {
        this.pages = pages
    }
}

In this example, the primary constructor is defined in the class header with val properties for title and author. The secondary constructor is declared using the constructor keyword, and it initializes the additional pages property using the this keyword and delegates to the primary constructor using : this(title, author).

Methods

In addition to properties, classes can have methods. Methods are functions associated with a class and can perform various operations. Here’s an example of a class with a method:

class Calculator {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
}

In this example, the Calculator class defines an add method that takes two integer parameters and returns their sum.

Access Modifiers

Kotlin provides access modifiers to control the visibility of class members (properties, methods, constructors). The common access modifiers are:

  • public (default): Visible everywhere.
  • private: Visible only within the class.
  • protected: Visible within the class and its subclasses.
  • internal: Visible within the module (a set of Kotlin files compiled together).

You can specify an access modifier before properties, methods, and constructors to control their visibility.

Command and Example

Here’s an example that demonstrates the use of classes, properties, constructors, and methods in Kotlin:

class Circle(val radius: Double) {
    fun calculateArea(): Double {
        return Math.PI * radius * radius
    }
}

fun main() {
    val circle = Circle(5.0)
    val area = circle.calculateArea()
    println("Circle with radius ${circle.radius} has an area of $area")
}

In this example, we have a Circle class with a primary constructor that takes a radius property. It also defines a method calculateArea to compute the area of the circle. The main function creates a Circle object and calculates its area.

Classes and objects are fundamental to object-oriented programming in Kotlin. They provide a structured way to define data and behavior, allowing you to create reusable and modular code. Understanding how to define classes, create objects, and work with properties and methods is essential for effective Kotlin development.