Kotlin Classes and Objects
A class is a blueprint. An object is the actual thing built from that blueprint. Think of a class as the architectural plan for a house — the plan itself is not a house. When you build using the plan, you get an actual house (an object). You can build many houses from one plan.
Defining a Class
class Car {
var brand: String = ""
var speed: Int = 0
fun accelerate(amount: Int) {
speed += amount
println("$brand is now going $speed km/h")
}
fun brake() {
speed = 0
println("$brand has stopped.")
}
}
The variables inside a class are called properties. The functions inside a class are called member functions or methods.
Creating Objects (Instances)
val car1 = Car() car1.brand = "Toyota" car1.speed = 0 car1.accelerate(60) // Toyota is now going 60 km/h val car2 = Car() car2.brand = "Honda" car2.accelerate(80) // Honda is now going 80 km/h
Diagram — Class and Objects
CLASS Car (Blueprint)
┌──────────────────────────┐
│ brand: String │
│ speed: Int │
│ accelerate(amount: Int) │
│ brake() │
└──────────────────────────┘
│
─────┴──────────────
│ │
OBJECT car1 OBJECT car2
brand = "Toyota" brand = "Honda"
speed = 60 speed = 80
Constructors
A constructor is a special function that runs when you create an object. It sets up the object's initial state. Kotlin's primary constructor lives right in the class header.
Primary Constructor
class Person(val name: String, val age: Int) {
fun introduce() {
println("Hi, I'm $name and I'm $age years old.")
}
}
val p1 = Person("Ananya", 25)
p1.introduce() // Hi, I'm Ananya and I'm 25 years old.
init Block
The init block runs immediately after the primary constructor. Use it for validation or setup logic.
class BankAccount(val owner: String, initialBalance: Double) {
var balance: Double = initialBalance
init {
require(initialBalance >= 0) { "Balance cannot be negative." }
println("Account created for $owner with ₹$balance")
}
}
val acc = BankAccount("Rohan", 5000.0)
// Account created for Rohan with ₹5000.0
Secondary Constructor
class Product {
var name: String
var price: Double
constructor(name: String, price: Double) {
this.name = name
this.price = price
}
constructor(name: String) : this(name, 0.0) {
println("$name added with no price set.")
}
}
Properties with Getters and Setters
Kotlin properties can have custom logic for reading (getter) and writing (setter) their values.
class Temperature(private var celsius: Double) {
val fahrenheit: Double
get() = celsius * 9 / 5 + 32
var kelvin: Double
get() = celsius + 273.15
set(value) { celsius = value - 273.15 }
}
val temp = Temperature(100.0)
println(temp.fahrenheit) // 212.0
println(temp.kelvin) // 373.15
Visibility Modifiers
Visibility modifiers control who can access a class member.
Modifier | Accessible From --------------|---------------------------------- public | Everywhere (default) private | Only inside the same class protected | Inside the class and subclasses internal | Anywhere in the same module
class Wallet {
private var balance: Double = 0.0 // hidden from outside
fun deposit(amount: Double) {
if (amount > 0) balance += amount
}
fun getBalance(): Double = balance
}
val w = Wallet()
w.deposit(500.0)
println(w.getBalance()) // 500.0
// println(w.balance) // ERROR: balance is private
Companion Objects — Class-Level Members
A companion object holds properties and functions that belong to the class itself, not to any single instance. It is similar to static members in Java.
class MathUtils {
companion object {
const val PI = 3.14159
fun circleArea(radius: Double): Double {
return PI * radius * radius
}
}
}
println(MathUtils.PI) // 3.14159
println(MathUtils.circleArea(5.0)) // 78.53975
// No object creation needed to call these.
