Thuta Learning
AdvancedProgrammingbeginner

Encapsulation

Relax. We'll talk through this in plain words — no textbook voice.

Encapsulation means keeping data private and controlling access to it through public methods. If you let data be edited freely, invalid values can sneak in — for example, you can check inside a setter to stop age from being set to -5. It's like putting the data in a lock box and handing out the key as a method.

java
class Person {
  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String newName) {
    name = newName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int newAge) {
    if (newAge >= 0) {
      age = newAge;
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Person person = new Person();
    person.setName("Aung");
    person.setAge(25);

    System.out.println(person.getName());
    System.out.println(person.getAge());
  }
}

name and age are private, so they can't be modified directly from outside the class. Getter methods return the value, and setter methods set it. setAge checks to block negative values from getting in.

You should see
Aung 25

Real-World Use

Sensitive data like user accounts, bank balances, subscription status, and wallet credits should be protected with encapsulation.

Easy traps

  • You can't modify a private field from outside like person.age = -5. You have to go through a getter/setter instead.
Encapsulation | Thuta Learning