Kotlin OOP
Object-oriented programming in Kotlin lets you model real-world things as objects that bundle data and behavior together.
What Is OOP?
Object-oriented programming (OOP) is a style of programming built around 'objects' rather than just functions and logic. An object combines state (properties) and behavior (functions) into a single unit. Kotlin is a fully object-oriented language, but it also blends in functional programming features, so you get the best of both worlds.
In Kotlin, almost everything is an object, and every piece of OOP code starts from a blueprint called a class. A class describes what properties and functions its objects will have, and an object is a concrete instance created from that blueprint.
The Four Pillars of OOP
Kotlin supports the four classic OOP pillars: encapsulation, abstraction, inheritance, and polymorphism. Encapsulation hides internal details behind a clean interface. Abstraction lets you work with simplified models instead of raw complexity. Inheritance lets one class reuse and extend another. Polymorphism lets different classes respond to the same call in their own way.
- Encapsulation - bundling data and methods, and controlling access with visibility modifiers
- Abstraction - exposing only what's necessary through classes and interfaces
- Inheritance - creating new classes based on existing ones using the open and : keywords
- Polymorphism - calling the same method name and getting different behavior depending on the object
Why Kotlin's OOP Feels Different
Kotlin was designed to reduce boilerplate compared to older OOP languages. Classes are concise, properties don't need separate getter and setter methods written by hand, and null safety is built into the type system so objects can't silently hold unexpected null references.
Your First Class and Object
class Car(val brand: String, val topSpeed: Int) {
fun describe(): String {
return "$brand can reach $topSpeed km/h"
}
}
fun main() {
val car = Car("Falcon", 220)
println(car.describe())
}Encapsulation Example
class BankAccount(private var balance: Double) {
fun deposit(amount: Double) {
if (amount > 0) balance += amount
}
fun getBalance(): Double = balance
}
fun main() {
val account = BankAccount(100.0)
account.deposit(50.0)
println(account.getBalance())
}Polymorphism Preview
open class Shape {
open fun area(): Double = 0.0
}
class Square(val side: Double) : Shape() {
override fun area(): Double = side * side
}
fun main() {
val shape: Shape = Square(4.0)
println(shape.area())
}The next lessons walk through classes and objects, constructors, class functions, and inheritance in detail, building up from these fundamentals one concept at a time.
Exercise: Kotlin OOP
Does Kotlin support object-oriented concepts such as classes and interfaces?