Classes and Objects in Kotlin

Classes and Objects

Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries; we'll start from the basics.

Classes and objects are the building blocks of OOP. A class acts as a blueprint for creating objects, which are instances of the class. Understanding these basics is essential before moving on to more advanced OOP topics like inheritance, polymorphism, and encapsulation.

Defining a Class

What is an Object?

An object is an instance of a class. It represents a specific example of the class and holds the characteristics that define the class.

Objects have three main characteristics:

  • State: The data or attributes of the object. In the Person class, the name and age represent the object's state.
  • Behavior: The methods and functions that the object can perform.
  • Identity: A unique identifier that distinguishes the object from others, even if they have the same state.

To understand object identity in Kotlin, consider this example:

fun main() {
    val person1 = Person("Alice", 25)
    val person2 = Person("Alice", 25)
    val person3 = person1

    println(person1 == person2)  // true (compares values)
    println(person1 === person2)  // false (compares references)
    println(person1 === person3)  // true (same object reference)
}

Using Constructors

Kotlin integrates the constructor directly into the class declaration as a primary constructor. You can initialize the object's properties using this constructor:

class Person(val name: String, val age: Int)

For more complex initialization, use the init block:

class Person(val name: String, val age: Int) {
    init {
        require(age > 0) { "Age must be positive" }
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal