Kotlin Classes
A class is a blueprint for creating objects. It defines the properties (data) and functions (behavior) that all objects of that type will have. Think of a class as a cookie cutter and objects as the individual cookies you make from it.
Defining a Class
class Car {
var brand: String = ""
var speed: Int = 0
fun accelerate(amount: Int) {
speed += amount
println("$brand accelerates to $speed km/h")
}
fun brake() {
speed = 0
println("$brand stops.")
}
}Creating Objects (Instances)
fun main() {
val car1 = Car()
car1.brand = "Toyota"
car1.accelerate(60)
car1.accelerate(30)
car1.brake()
val car2 = Car()
car2.brand = "Honda"
car2.accelerate(80)
}Output:
Toyota accelerates to 60 km/h
Toyota accelerates to 90 km/h
Toyota stops.
Honda accelerates to 80 km/hClass vs Object: Blueprint vs Product
Class (the blueprint):
class Car { brand, speed, accelerate(), brake() }
↓ defined once
Objects (the products):
val car1 = Car() → brand="Toyota", speed=90
val car2 = Car() → brand="Honda", speed=80
val car3 = Car() → brand="BMW", speed=0
Each object has its own data, but shares the same structure.
Primary Constructor
class Person(val name: String, val age: Int) {
fun greet() {
println("Hi, I'm $name and I'm $age years old.")
}
}
fun main() {
val p1 = Person("Alice", 30)
val p2 = Person("Bob", 25)
p1.greet() // Hi, I'm Alice and I'm 30 years old.
p2.greet() // Hi, I'm Bob and I'm 25 years old.
}Init Block
The init block runs automatically when an object is created:
class BankAccount(val owner: String, initialBalance: Double) {
var balance: Double = initialBalance
init {
println("Account created for $owner with ₹$balance")
require(initialBalance >= 0) { "Balance cannot be negative" }
}
fun deposit(amount: Double) {
balance += amount
println("Deposited ₹$amount. New balance: ₹$balance")
}
}
fun main() {
val acc = BankAccount("Priya", 5000.0)
acc.deposit(2000.0)
}Output:
Account created for Priya with ₹5000.0
Deposited ₹2000.0. New balance: ₹7000.0Member Functions
class Rectangle(val width: Double, val height: Double) {
fun area(): Double = width * height
fun perimeter(): Double = 2 * (width + height)
fun isSquare(): Boolean = width == height
override fun toString(): String = "Rectangle(${width}×${height})"
}
fun main() {
val r = Rectangle(6.0, 4.0)
println(r) // Rectangle(6.0×4.0)
println("Area: ${r.area()}") // Area: 24.0
println("Perimeter: ${r.perimeter()}") // Perimeter: 20.0
println("Is square: ${r.isSquare()}") // Is square: false
}Visibility Modifiers
Modifier │ Visible from
───────────┼───────────────────────────────────
public │ everywhere (default)
private │ only inside this class
protected │ this class and subclasses
internal │ same module (same project/library)
class UserAccount(val username: String) {
private var password: String = "" // hidden from outside
fun setPassword(newPass: String) {
if (newPass.length >= 8) {
password = newPass
println("Password updated")
} else {
println("Password too short")
}
}
fun login(attempt: String): Boolean = attempt == password
}