Encapsulation ซ่อนข้อมูลสำคัญ ทำตัวแปร private ให้ getter/setter public
ตัวอย่างใน JShell
jshell> class Employee {
private String firstName, lastName, designation, location;
public Employee(String fn, String ln, String desig, String loc) {
this.firstName = fn; this.lastName = ln;
this.designation = desig; this.location = loc;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String getJobDesignation() { return designation; }
public String getLocation() { return location; }
public String toString() {
return "Name = " + firstName + ", " + lastName + " | " +
"Job designation = " + designation + " | " +
"location = " + location + ".";
}
}
| created class Employee
jshell> Employee emp = new Employee("Jai", "Adithya", "Content Developer", "Hyderabad")
emp ==> Name = Jai, Adithya | Job designation = Content Developer | location = Hyderabad.
ตัวแปร private เข้าถึงได้เฉพาะผ่าน getter methods