class Counter { var count = 0 fun increment() { count += 1 } } fun main() { val counter = Counter() counter.increment() counter.increment() println(counter.count) }
The Counter class has a variable count starting at 0. Each call to increment() adds 1 to count. Since increment() is called twice, the final count is 2.
Classes group data and the functions that work on that data. This makes code easier to understand, maintain, and reuse, similar to how a toolbox keeps related tools together.
class BankAccount { var balance: Double fun deposit(amount: Double) { balance += amount } } fun main() { val account = BankAccount() account.deposit(100.0) println(account.balance) }
The balance variable is declared but not initialized. Kotlin requires non-nullable variables to be initialized before use, causing a compilation error.
class LightSwitch { var isOn = false fun toggle() { isOn = !isOn } } fun main() { val switch = LightSwitch() switch.toggle() switch.toggle() switch.toggle() println(switch.isOn) }
The isOn starts as false. Each toggle() flips it. After three toggles: false → true → false → true. So the output is true.
Encapsulation means keeping the internal data (state) hidden inside the class and only allowing access through defined functions (behavior). This protects the data from unwanted changes.