Kotlin Classes

Creating blueprints for objects

🏗️ What are Classes?

Classes in Kotlin are blueprints for creating objects. They define properties (data) and functions (behavior) that objects will have. Think of a class as a template for making similar things.


// Simple class definition
class Car {
    var brand = "Unknown"
    var model = "Unknown"
    
    fun start() {
        println("$brand $model is starting...")
    }
}
                                    

Usage:

val myCar = Car()
myCar.brand = "Toyota"
myCar.start() // Toyota Unknown is starting...

Key Class Concepts

📦

Properties

Variables that store data

var name: String = "John"
⚙️

Functions

Actions the class can perform

fun speak() { println("Hello") }
🎯

Objects

Instances created from classes

val person = Person()
🔒

Encapsulation

Controlling access to data

private var age: Int = 0

🔹 Basic Class Structure

Here's how to create a simple class with properties and functions:

class Person {
    // Properties (variables)
    var name: String = ""
    var age: Int = 0
    
    // Functions (methods)
    fun introduce() {
        println("Hi, I'm $name and I'm $age years old")
    }
    
    fun haveBirthday() {
        age++
        println("Happy birthday! Now I'm $age")
    }
}

fun main() {
    val person = Person()
    person.name = "Alice"
    person.age = 25
    person.introduce()
    person.haveBirthday()
}

Output:

Hi, I'm Alice and I'm 25 years old
Happy birthday! Now I'm 26

🔹 Class with Primary Constructor

You can initialize properties directly when creating an object:

class Dog(var name: String, var breed: String) {
    fun bark() {
        println("$name the $breed says: Woof!")
    }
    
    fun fetch() {
        println("$name is fetching the ball!")
    }
}

fun main() {
    val myDog = Dog("Buddy", "Golden Retriever")
    myDog.bark()
    myDog.fetch()
}

Output:

Buddy the Golden Retriever says: Woof!
Buddy is fetching the ball!

🔹 Private Properties

Use private to hide data and provide controlled access:

class BankAccount(private var balance: Double) {
    
    fun deposit(amount: Double) {
        if (amount > 0) {
            balance += amount
            println("Deposited $amount. New balance: $balance")
        }
    }
    
    fun withdraw(amount: Double) {
        if (amount > 0 && amount <= balance) {
            balance -= amount
            println("Withdrew $amount. New balance: $balance")
        } else {
            println("Insufficient funds!")
        }
    }
    
    fun getBalance(): Double {
        return balance
    }
}

fun main() {
    val account = BankAccount(100.0)
    account.deposit(50.0)
    account.withdraw(30.0)
    println("Current balance: ${account.getBalance()}")
}

Output:

Deposited 50.0. New balance: 150.0
Withdrew 30.0. New balance: 120.0
Current balance: 120.0

🧠 Test Your Knowledge

What keyword is used to create a class in Kotlin?