Loading lessons...
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 fieldxxx.setXxx(value)updates the private fieldxxx.
TL;DR
- Encapsulation hides data behind private fields.
- Getters read the data; setters update it.
thisrefers to the current object.