Kotlin Classes and Objects: The Core of Object-Oriented Programming 🚀
Imagine you're a car manufacturer 🚗. You want to create multiple cars with similar properties but different details like color, model, and speed.
Instead of building each car from scratch, you design a blueprint (a class) and use it to create different cars (objects).
This is exactly how classes and objects work in Kotlin!
📌 In this blog, we’ll explore:
✅ What are Classes and Objects? 🤔
✅ Defining a Class in Kotlin 🏗️
✅ Creating Objects from a Class 🚗
✅ Class Constructors (Primary & Secondary) 🔨
✅ Properties and Methods 🛠️
✅ Visibility Modifiers 🔒
✅ Data Classes for Easy Modeling 📊
✅ Real-World Applications 🌍
1️⃣ What are Classes and Objects? 🤔
📌 A class is a blueprint for creating objects. It defines:
- Properties (variables) 🏷️
- Methods (functions) ⚙️
📌 An object is an instance of a class.
💡 Example Analogy:
- 🏠 Class → Blueprint of a house.
- 🏡 Object → A real house built from that blueprint.
2️⃣ Defining a Class in Kotlin 🏗️
🔹 Simple Class Definition
class Car {
var brand: String = "Toyota"
var speed: Int = 0
fun accelerate() {
speed += 10
println("The car is now going at $speed km/h")
}
}
✅ This defines a Car
class with two properties (brand
, speed
) and a method (accelerate()
).
3️⃣ Creating Objects from a Class 🚗
🔹 Creating an Object
val myCar = Car() // Creating an instance of Car
println(myCar.brand) // Output: Toyota
myCar.accelerate() // Output: The car is now going at 10 km/h
✅ Each object gets its own copy of the properties and methods!
4️⃣ Class Constructors (Primary & Secondary) 🔨
🔹 Primary Constructor (Short & Clean)
class Car(val brand: String, var speed: Int) {
fun accelerate() {
speed += 10
println("$brand is now going at $speed km/h")
}
}
val car1 = Car("Tesla", 0)
car1.accelerate() // Output: Tesla is now going at 10 km/h
✅ No need to declare brand
and speed
separately. The constructor does it!
🔹 Secondary Constructor (Extra Initialization)
class Car {
var brand: String
var speed: Int
constructor(brand: String, speed: Int) {
this.brand = brand
this.speed = speed
}
}
✅ Use secondary constructors when additional setup is needed.
5️⃣ Properties and Methods 🛠️
🔹 Adding More Methods
class Car(val brand: String, var speed: Int) {
fun accelerate() {
speed += 10
println("$brand is now going at $speed km/h")
}
fun brake() {
speed -= 10
println("$brand slowed down to $speed km/h")
}
}
val car = Car("Honda", 50)
car.accelerate() // Output: Honda is now going at 60 km/h
car.brake() // Output: Honda slowed down to 50 km/h
✅ Objects interact with their own properties and methods!
6️⃣ Visibility Modifiers 🔒
📌 Control who can access properties and methods.
Modifier | Access Level |
---|---|
public |
Default. Accessible from anywhere. |
private |
Accessible only inside the class. |
protected |
Accessible inside the class and subclasses. |
internal |
Accessible within the same module. |
🔹 Example: Using private
class BankAccount(private var balance: Double) {
fun deposit(amount: Double) {
balance += amount
println("Deposited $$amount. New balance: $$balance")
}
fun withdraw(amount: Double) {
if (amount <= balance) {
balance -= amount
println("Withdrew $$amount. Remaining balance: $$balance")
} else {
println("Insufficient funds!")
}
}
}
val account = BankAccount(1000.0)
account.deposit(500.0) // Output: Deposited $500.0. New balance: $1500.0
account.withdraw(2000.0) // Output: Insufficient funds!
✅ balance
is private, so it can’t be modified directly from outside.
7️⃣ Data Classes for Easy Modeling 📊
📌 Used for holding data with built-in toString()
, equals()
, and copy()
.
🔹 Example:
data class User(val name: String, val age: Int)
val user1 = User("Alice", 25)
println(user1) // Output: User(name=Alice, age=25)
val user2 = user1.copy(age = 30)
println(user2) // Output: User(name=Alice, age=30)
✅ No need to manually define toString()
or equals()
.
8️⃣ Real-World Applications 🌍
🔹 1. Modeling a Student System
class Student(val name: String, var grade: Int) {
fun promote() {
grade += 1
println("$name is now in grade $grade!")
}
}
val student = Student("John", 10)
student.promote() // Output: John is now in grade 11!
✅ Used in schools and universities to manage student details.
🔹 2. Creating a Simple Inventory System
class Product(val name: String, var price: Double) {
fun applyDiscount(discount: Double) {
price -= price * (discount / 100)
println("New price of $name: $$price")
}
}
val laptop = Product("Laptop", 1000.0)
laptop.applyDiscount(10.0) // Output: New price of Laptop: $900.0
✅ Used in e-commerce and retail systems.
🔟 Conclusion: Object-Oriented Power in Kotlin 🎯
✅ Classes act as blueprints for objects.
✅ Objects are created from classes and have properties & methods.
✅ Constructors simplify object creation.
✅ Visibility modifiers protect data.
✅ Data classes are useful for modeling data.
💡 Now, go ahead and create your own Kotlin classes! 🚀
💬 What would you like to model using Kotlin classes? Let me know in the comments! ⬇️😊