Learn Kotlin · 7/18

Object-Oriented Programming I: Classes and Objects

8 min read

Object-Oriented Programming I: Classes and Objects 🐘

Welcome to the fascinating world of Object-Oriented Programming (OOP) in Kotlin! Before we dive in, let's address a fundamental question: why do we even need this?

Imagine you're building a complex application, say, a system to manage a library. You'd have to keep track of books, members, and their borrowings. Without a structured way to organize your code, you'd end up with a chaotic mess of variables and functions. It would be like trying to find a specific book in a library where all the books are just thrown in a giant pile. OOP provides a way to structure our code into reusable blueprints, making it organized, manageable, and scalable.


1. Classes and Primary Constructors 🏗️

Definition: A class in Kotlin is a blueprint for creating objects. An object is an instance of a class.

The Problem: We need a way to model real-world entities or concepts in our code. For our library system, we need a blueprint for what a "Book" is. Every book will have a title, author, and an ISBN.

The Solution: We can create a Book class.

kotlin
class Book(val title: String, val author: String, val isbn: String)

Let's break this down:

  • class Book: This declares a class named Book.
  • (val title: String, val author: String, val isbn: String): This is the primary constructor. It's a concise way to declare properties and initialize them when an object of the class is created.
    • val: This keyword declares a read-only property. Once a book object is created with a title, you can't change it. If you wanted to be able to change it, you would use var.
    • title: String: This declares a property named title of type String.

Now, we can create instances (objects) of our Book class:

kotlin
fun main() {
    val theHobbit = Book("The Hobbit", "J.R.R. Tolkien", "978-0-345-33968-3")
    val prideAndPrejudice = Book("Pride and Prejudice", "Jane Austen", "978-1-5032-9056-3")

    println(theHobbit.title) // Output: The Hobbit
    println(prideAndPrejudice.author) // Output: Jane Austen
}

Think of the Book class as the architectural blueprint for a house. The blueprint itself isn't a house, but it defines the properties of the house (number of rooms, floors, etc.). Each house you build from that blueprint (theHobbit, prideAndPrejudice) is an object, a concrete instance.

Interesting Fact: In Kotlin, if a class has no body, you can omit the curly braces {}. How cool and concise is that!


2. Properties: Getters, Setters, and Field Backing 🚪

Definition: Properties in Kotlin classes are variables that can have custom accessor methods (getters and setters). A backing field is an internal field that holds the value of a property.

The Problem: Sometimes, you need more control over how a property's value is accessed or modified. For instance, what if we want to ensure that a book's title is never an empty string?

The Solution: Kotlin provides a clean way to define custom getters and setters.

Under the hood, when you declare a property like val title: String, Kotlin automatically generates a "getter" method for you. If you use var, it generates both a "getter" and a "setter".

Let's see a custom setter in action. Imagine we have a Member class for our library.

kotlin
class Member(var name: String) {
    var address: String = ""
        set(value) {
            if (value.isNotBlank()) {
                field = value
            }
        }
}

fun main() {
    val member = Member("John Doe")
    member.address = "  " // This will be ignored because of our custom setter logic
    println(member.address) // Output: "" (the initial value)

    member.address = "123 Main St"
    println(member.address) // Output: 123 Main St
}
  • set(value): This is the custom setter. value is the conventional name for the new value being assigned.
  • field: This is the backing field. It's a special identifier you can only use inside the accessors (getter and setter). It holds the actual value of the property. You can't access field directly from outside the property's accessors. This prevents an infinite loop, because if you were to write address = value inside the setter, it would call the setter again, and again, and... you get the picture. 💥

Custom getters are useful too. Let's say we want to get a formatted description of a book.

kotlin
class Book(val title: String, val author: String) {
    val description: String
        get() = "$title by $author"
}

fun main() {
    val book = Book("1984", "George Orwell")
    println(book.description) // Output: 1984 by George Orwell
}

Here, the description property doesn't have a backing field because its value is computed on the fly by the getter.

Industry Practice: Custom setters are very common for validation. You want to ensure the data in your objects is always valid.


3. The 'init' Block and Secondary Constructors 🛠️

The Problem: What if you need to perform some logic right after an object is created, like printing a welcome message or performing some calculations? Or what if you need multiple ways to create an object?

The Solution: The init block and secondary constructors.

The init Block

The init block is an initializer block. The code inside it is executed when an object is created, right after the primary constructor is called. You can have multiple init blocks, and they will be executed in the order they appear in the class body.

kotlin
class Car(val make: String, val model: String, val year: Int) {

    init {
        println("A new car has been created: $year $make $model.")
    }

    init {
        // You can have more than one!
        println("This car is ready to drive!")
    }
}

fun main() {
    val myCar = Car("Toyota", "Camry", 2024)
}

When you run this, you'll see:

oxygene
A new car has been created: 2024 Toyota Camry.
This car is ready to drive!

Secondary Constructors

Sometimes you need to provide different ways to create an object. For example, maybe you want to create a Book object sometimes with just a title and author, and add the ISBN later. For this, you can use a secondary constructor.

A secondary constructor must call the primary constructor (or another secondary constructor that eventually calls the primary one) using the this keyword.

kotlin
class Book(val title: String, val author: String, val isbn: String) {

    // Secondary constructor
    constructor(title: String, author: String) : this(title, author, "N/A") {
        println("Created a book without an ISBN.")
    }
}

fun main() {
    val book1 = Book("The Catcher in the Rye", "J.D. Salinger", "978-0-316-76948-0")
    val book2 = Book("To Kill a Mockingbird", "Harper Lee")

    println(book2.isbn) // Output: N/A
}

When book2 is created, the secondary constructor is called, which then calls the primary constructor with a default value for isbn.

Funny Exaggeration: Think of the primary constructor as the main entrance to a building. Secondary constructors are like side doors, but eventually, everyone has to go through the main entrance area (this(...)) to get inside properly.


4. Visibility Modifiers: Public, Private, Protected, Internal 🕵️

Definition: Visibility modifiers are keywords that control the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters.

The Problem: In a large project, you want to control which parts of your code can access other parts. This is crucial for preventing accidental modifications and for creating a clean, maintainable architecture. You don't want someone from the "billing" part of your code to be able to directly change the "user authentication" logic.

The Solution: Kotlin provides four visibility modifiers.

  • public (the default): Visible everywhere. If you don't specify a modifier, it's public.
  • private: Visible only inside the class where it is declared.
  • protected: Visible inside the class where it is declared and in its subclasses.
  • internal: Visible inside the same module. A module is a set of Kotlin files compiled together (e.g., a Gradle project).

Let's see them in a Library simulation:

kotlin
// In file LibrarySystem.kt (part of 'library' module)

open class LibraryItem(val title: String) {
    private fun canBeBorrowed(): Boolean {
        // Complex internal logic to check availability
        return true
    }

    protected fun checkOut() {
        if (canBeBorrowed()) {
            println("$title has been checked out.")
        }
    }
}

class Book(title: String) : LibraryItem(title) {
    fun borrow() {
        checkOut() // Can access protected 'checkOut'
        // canBeBorrowed() // Error: cannot access 'canBeBorrowed', it is private in 'LibraryItem'
    }
}

internal class LibraryManagement {
    fun generateReport() {
        // Can be accessed from anywhere inside the 'library' module
        println("Generating library report...")
    }
}

fun main() {
    val book = Book("A Brief History of Time")
    book.borrow()
    // book.checkOut() // Error: 'checkOut' is protected and cannot be accessed outside the class hierarchy

    val management = LibraryManagement()
    management.generateReport()
}

// In another file in a different module
// val management = LibraryManagement() // Error: 'LibraryManagement' is internal and cannot be accessed here

Real-world Scenario: Think of a car. The steering wheel and pedals are public—anyone driving the car can use them. The engine's internal workings are private—you're not supposed to mess with them directly while driving. Some diagnostic ports might be protected, accessible to mechanics (subclasses of "CarUser"). The special tools used at the factory are internal to the car manufacturer's module.

Industry Standard: It's a good practice to make everything as private as possible and only expose what is absolutely necessary. This principle is called encapsulation.


Further Reading 📚

Challenge

Your task is to implement a CorporateEmployee class in Kotlin that models an employee profile within a company's HR system. This class must enforce data integrity and provide different ways to be instantiated.

Requirements:

  1. Primary Constructor: The class must have a primary constructor that accepts three parameters: a read-only employeeId (String), a mutable department (String), and a mutable securityLevel (Int).

  2. init Block: Immediately after an object is created, an init block should validate that the initial securityLevel is within the valid range of 1 to 5 (inclusive). If it is not, it should throw an IllegalArgumentException.

  3. Visibility & Encapsulation:

    • Create a private mutable property named accessKey of type String.
    • This accessKey should be initialized internally within the class to a value generated by combining the employeeId and a fixed secret, for example: "KEY-" + employeeId + "-SECRET".
    • All other properties (employeeId, department, securityLevel) should be publicly accessible.
  4. Custom Setter: The securityLevel property must have a custom setter. This setter should perform the same validation as the init block (level must be between 1 and 5). If the validation fails, it should throw an IllegalArgumentException.

  5. Computed Property (Custom Getter): Create a read-only computed property named employeeCardInfo of type String. This property should return a formatted string combining the employee's public information: "ID: [employeeId] | Department: [department]".

  6. Secondary Constructor: Implement a secondary constructor that allows creating a CorporateEmployee object with only an employeeId. This constructor should delegate to the primary constructor, setting the department to "Unassigned" and the securityLevel to 1.

Expected result

Your code should define a CorporateEmployee class with the following characteristics:

  • A primary constructor with the signature (val employeeId: String, var department: String, var securityLevel: Int).
  • An init block that validates the initial securityLevel is between 1 and 5.
  • A private var accessKey: String that is initialized internally.
  • A custom set implementation for the securityLevel property that validates the new value is between 1 and 5.
  • A read-only val property named employeeCardInfo with a custom get implementation that returns the correctly formatted string.
  • A secondary constructor with the signature constructor(employeeId: String) which properly delegates to the primary constructor with default values for department and securityLevel.
kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.