0
0
Kotlinprogramming~3 mins

Why Visibility modifiers (public, private, internal, protected) in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code had secret rooms only trusted friends could enter?

The Scenario

Imagine you are building a big house with many rooms, but you want to keep some rooms locked so only certain people can enter. Without locks, anyone can wander everywhere, causing confusion and mistakes.

The Problem

Without visibility controls, all parts of your code are open to everyone. This means anyone can change or use things they shouldn't, leading to bugs and security problems. It's like leaving all your doors wide open.

The Solution

Visibility modifiers act like locks on your code's rooms. They let you decide who can see or use each part, keeping your code safe, organized, and easier to manage.

Before vs After
Before
class BankAccount {
    var balance = 0
}
// Anyone can change balance directly
After
class BankAccount {
    private var balance = 0
    fun deposit(amount: Int) { balance += amount }
}
// balance is protected inside the class
What It Enables

It lets you protect important parts of your code so only the right pieces can access or change them, making your programs safer and easier to fix.

Real Life Example

Think of a bank app where the user can deposit money but cannot directly change the balance number. Visibility modifiers keep the balance hidden and safe inside the app.

Key Takeaways

Visibility modifiers control who can see or use parts of your code.

They prevent accidental or harmful changes by restricting access.

This leads to safer, cleaner, and more reliable programs.