Access Modifiers: public, private, protected
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.
Java provides access modifiers to control what parts of your code are visible to other parts.
There are four main levels:
public:
The class, method, or field is accessible from anywhere.
If something is public, any other class can use it.
private:
The member is accessible only inside its own class.
No external class can see or change it directly.
protected:
The member is accessible inside its own package and also by subclasses (even in different packages).
Mostly used in inheritance scenarios.
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.
Below is an example showing how to use access modifiers to protect a classโs data.
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