Skip to lesson

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

OpenFieldsDemo.javaJava
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);    }}
Output
Class average: 20

What this code does

  • -40 is a valid int, 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".

A Student object keeps marks = 85 in a private inside. Code in another class can go in only through the public doors: s.setMarks(85) is checked, then saved, and s.getMarks() reads 85. s.marks = -40 hits the wall: marks has private access in Student.
A bank works the same way. You cannot walk into the vault and take cash; you go to the counter, and the cashier checks your slip and balance first.

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

CheckedDemo.javaJava
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);    }}
Output
Refused -40 for Kavya
Class average: 60

What this code does

  • marks is private, so the only way to change it is setMarks, and setMarks checks the range first.
  • -40 is refused before it reaches the field. getMarks() lets main read the value without being able to change it.

Example 3 · Trying to go around the method

BypassDemo.javaJava
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;    }}
Sample compiler output
BypassDemo.java:14: error: marks has private access in Student
        k.marks = -40;
         ^
1 error

What this code does

  • A private field can be used only by code inside its own class. BypassDemo is a different class, so javac stops.
  • 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

PhoneDemo.javaJava
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() + "%");    }}
Output
After charging: 100%
After a video: 70%
After a long game: 0%

What this code does

  • Callers think in actions, charge and use, not in raw numbers. The class keeps the value between 0 and 100.
  • No code outside Phone can 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