Encapsulation means hiding internal data and controlling access through methods. Fields are private — only the class itself can access them directly. External code uses getters and setters. This prevents invalid state and makes code easier to maintain.
| Modifier | Same Class | Same Package | Subclass | Everywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| (default) | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
public class Employee {
private String name;
private double salary;
private String department;
public Employee(String name, double salary, String department) {
this.name = name;
setSalary(salary);
this.department = department;
}
// Getter
public String getName() {
return name;
}
// Setter with validation
public void setSalary(double salary) {
if (salary < 0) {
throw new IllegalArgumentException("Salary cannot be negative");
}
this.salary = salary;
}
public double getSalary() {
return salary;
}
public String getDepartment() {
return department;
}
}public class EmployeeTest {
public static void main(String[] args) {
Employee emp = new Employee("Alice", 75000, "QA");
System.out.println(emp.getName()); // Alice
System.out.println(emp.getSalary()); // 75000.0
System.out.println(emp.getDepartment()); // QA
emp.setSalary(80000); // valid
System.out.println(emp.getSalary()); // 80000.0
// emp.name = "Bob"; // Compile error — private
// emp.setSalary(-100); // Runtime error — validation catches it
}
}In automation frameworks, page object fields (locators) are typically private. Tests interact with pages through public methods like login(), getErrorMessage(), isLogoutVisible() — never by directly accessing locators.
Q: What is encapsulation and why is it important?
A: Encapsulation bundles data (fields) and the methods that operate on it into a single unit (class), and restricts direct access to the data using access modifiers. It is important because: (1) Data integrity — setters can validate input before assignment. (2) Flexibility — you can change internal implementation without breaking external code. (3) Security — sensitive data like passwords cannot be accessed directly.
Exercise 1: Create a BankAccount class with private fields (accountNumber, balance, holderName). Add getters for all fields, but only a setter for holderName (account number should not be changeable after creation). Add a deposit and withdraw method with validation.
Exercise 2: Why would you make a getter return a copy of a list instead of the list itself? Think about what happens if external code modifies the returned list.