allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œHardships often prepare ordinary people for an extraordinary destiny.โ€
[C.S. Lewis (1898โ€“1963) โ€“ British writer, theologian, author of The Chronicles of Narnia]


Access Modifiers: public, private, protected


10.1.1 What is Encapsulation?

Encapsulation is one of the four core pillars of object-oriented programming (OOP) (along with Inheritance, Polymorphism, and Abstraction).
Encapsulation means hiding internal details of how an object works and exposing only what is needed to the outside world.

In simple terms, encapsulation is like:

  • Locking your valuables inside a safe.

  • Giving people only the key or buttons they need to access specific things.

  • Keeping your internal data safe from accidental or unauthorized changes.

Why do we need it?
Because when programs grow, data must be protected.
Without proper encapsulation, anyone can reach into your class and change its fields in unexpected ways โ€” which breaks rules and causes bugs.


10.1.2 Role of Access Modifiers

Java provides access modifiers to control what parts of your code are visible to other parts.

There are four main levels:

  1. public:
    The class, method, or field is accessible from anywhere.
    If something is public, any other class can use it.

  2. private:
    The member is accessible only inside its own class.
    No external class can see or change it directly.

  3. protected:
    The member is accessible inside its own package and also by subclasses (even in different packages).
    Mostly used in inheritance scenarios.

  4. default (package-private):
    If you donโ€™t write an explicit modifier, itโ€™s package-private by default.
    The member is accessible only to other classes in the same package.


In real OOP design:

  • Fields are usually private โ€” because data should be controlled.

  • Methods that need to be reused are public โ€” this is the safe access point.

  • Helper methods can be private โ€” internal tools for the class only.


10.1.3 Example: Using Access Modifiers

Below is an example showing how to use access modifiers to protect a classโ€™s data.

java
public class BankAccount { private double balance; // private field public void deposit(double amount) { if (amount > 0) { balance += amount; } } public double getBalance() { return balance; } }

Key points:

  • balance is private: no one can change it directly.

  • deposit is public: provides safe, validated way to add money.

  • getBalance is public: provides read-only access to the balance.

Without private, anyone could write account.balance = -5000; and break your business logic.

Access Modifiers + Getters/Setters = Core Encapsulation Pattern