Why encapsulation?
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)If any code can set a bank balance to -5000 directly, no rule can protect it. You need a way to keep data safe inside the class.
The problem with open fields
Encapsulation is the wrapping of data (fields) and the methods that work on that data into a single unit, the class, while hiding the data from direct access outside the class (private fields) and allowing access only through the class's methods.
Any code can write k.marks = -40;, and Java accepts it. Java checks the type of a value, not whether it makes sense: -40 is a valid int, so javac is happy.
Example 1 · Open fields accept wrong values
class Student { String name; int marks;}
public class OpenFieldsDemo { public static void main(String[] args) { Student a = new Student(); a.name = "Aarav"; a.marks = 80;
Student k = new Student(); k.name = "Kavya"; k.marks = -40; // typing mistake: should be 40
int average = (a.marks + k.marks) / 2; System.out.println("Class average: " + average); }}Class average: 20
What this code does
-40is a validint, so Java accepts it. The compiler checks types, not meaning.- The wrong value spreads into the average. The real average is 60, but the program prints 20 with no error.
The wrong value does not stay in one place. It flows into totals, averages and results, and nothing reports it. Any line in any class could have set it, so the bug is hard to find.
What encapsulation means
Data hiding means making a class's fields private, so that no code outside the class can read or change them directly. It is one part of encapsulation; the class's methods that control access are the other part.
Think of a medicine capsule: the medicine and its shell come as one unit, and the shell keeps the powder inside. A class is that capsule: its fields and its methods are packed together, and the private fields stay inside.
Public methods (methods any class may call) are the only doors in. The doors hold the rules, such as "marks must be 0 to 100".
Private fields, public methods
Kavya's marks were typed as -40. Make marks private, as in Access modifiers (opens in a new tab), and give Student a setMarks method that checks the range before saving, plus getMarks to read it.
Example 2 · A private field behind a checking method
class Student { private String name; private int marks;
public Student(String name) { this.name = name; }
public void setMarks(int marks) { if (marks < 0 || marks > 100) { System.out.println("Refused " + marks + " for " + name); return; } this.marks = marks; }
public int getMarks() { return marks; }}
public class CheckedDemo { public static void main(String[] args) { Student a = new Student("Aarav"); Student k = new Student("Kavya"); a.setMarks(80); k.setMarks(-40); k.setMarks(40); int average = (a.getMarks() + k.getMarks()) / 2; System.out.println("Class average: " + average); }}Refused -40 for Kavya Class average: 60
What this code does
marksisprivate, so the only way to change it issetMarks, andsetMarkschecks the range first.-40is refused before it reaches the field.getMarks()letsmainread the value without being able to change it.
Example 3 · Trying to go around the method
class Student { private int marks;
public void setMarks(int marks) { if (marks >= 0 && marks <= 100) { this.marks = marks; } }}
public class BypassDemo { public static void main(String[] args) { Student k = new Student(); k.marks = -40; }}BypassDemo.java:14: error: marks has private access in Student
k.marks = -40;
^
1 errorWhat this code does
- A
privatefield can be used only by code inside its own class.BypassDemois a different class, sojavacstops. - This is what we want: the mistake is caught when you compile, not when a user sees a wrong result.
The recipe is the same for every class: make each field private, add a method that returns the value if outside code must read it, and add a method that changes it with the check inside. Getters and setters (opens in a new tab) gives these methods their usual names.
What you gain
A phone's battery must stay between 0 and 100. When the class owns the field, it keeps that rule itself, inside the methods charge and use.
Example 4 · The class owns the rule: battery stays 0 to 100
class Phone { private int battery; // percent, always 0 to 100
public void charge(int percent) { battery = battery + percent; if (battery > 100) { battery = 100; } }
public void use(int percent) { battery = battery - percent; if (battery < 0) { battery = 0; } }
public int getBattery() { return battery; }}
public class PhoneDemo { public static void main(String[] args) { Phone p = new Phone(); p.charge(70); p.charge(50); System.out.println("After charging: " + p.getBattery() + "%"); p.use(30); System.out.println("After a video: " + p.getBattery() + "%"); p.use(90); System.out.println("After a long game: " + p.getBattery() + "%"); }}After charging: 100% After a video: 70% After a long game: 0%
What this code does
- Callers think in actions,
chargeanduse, not in raw numbers. The class keeps the value between 0 and 100. - No code outside
Phonecan make the battery 120% or -20%. The rule is written once, inside the class.
Encapsulation is not about secrets: anyone can read your source code. It protects the object from wrong use by other code, including your own code written in a hurry. What you gain:
- Correct objects: a wrong value is stopped at the door, before it is saved.
- One place for each rule: the check lives in one method, not in fifty places in
main. - Easy bug hunting: only the class can change its fields, so you look in one class.
- Freedom to change the inside: you can rename a field or store it differently; callers keep calling the same methods.
Next step
Check your understanding
10 quick questions