Lesson 31 +10 XP

Encapsulation

Encapsulation

Encapsulation means keeping an object's data private and providing controlled access through methods.

Why encapsulate

  • Protect data from accidental changes.
  • Control how fields are read and written.
  • Hide the inner details of how a class works.

Private fields with getters and setters

public class Person {
  private String name;

  public String getName() {
    return name;
  }

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

Using the class

Person myObj = new Person();
myObj.setName("John");
System.out.println(myObj.getName());

The this keyword

Inside setName, this.name refers to the object's own field, so it is not confused with the parameter newName.

Getter and setter rules

  • getXxx() returns the private field xxx.
  • setXxx(value) updates the private field xxx.

TL;DR

  • Encapsulation hides data behind private fields.
  • Getters read the data; setters update it.
  • this refers to the current object.