Java > Object-Oriented Programming (OOP) > Encapsulation > Private Fields and Public Methods

Another Example: `Employee` Class with Encapsulation

This snippet further illustrates encapsulation using an `Employee` class. It shows how to protect sensitive data like salary and provides controlled access through getters and setters with validation.

Code Example: `Employee` Class

The `Employee` class demonstrates encapsulation by making the `name`, `employeeId`, and `salary` fields private. The `getSalary()` method allows access to the salary, while the `setSalary()` method allows modification but includes a validation check to ensure the salary is a positive value. If an attempt is made to set a negative salary, an error message is printed, and the salary is not updated. The name and employeeId are immutable as they don't have the setter method, they are set in the constructor.

public class Employee {
    private String name;
    private String employeeId;
    private double salary;

    public Employee(String name, String employeeId, double salary) {
        this.name = name;
        this.employeeId = employeeId;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        if (salary > 0) {
            this.salary = salary;
        } else {
            System.out.println("Invalid salary value.");
        }
    }

    public static void main(String[] args) {
        Employee employee = new Employee("John Doe", "E12345", 50000.0);
        System.out.println("Employee Name: " + employee.getName());
        System.out.println("Employee ID: " + employee.getEmployeeId());
        System.out.println("Salary: " + employee.getSalary());
        employee.setSalary(55000.0);
        System.out.println("New Salary: " + employee.getSalary());
        employee.setSalary(-1000.0);
        System.out.println("Salary after invalid attempt: " + employee.getSalary());
    }
}

Benefits of Encapsulation in this Example

  • Data Integrity: The `setSalary()` method prevents the salary from being set to a negative value, ensuring data integrity.
  • Controlled Access: The private fields can only be accessed or modified through the public getter and setter methods, allowing for controlled access.
  • Flexibility: The internal implementation of the `Employee` class can be changed without affecting external code that uses it. For example, the way salary is calculated could be changed without modifying the public interface.

Further Enhancements

This `Employee` class could be further enhanced by:

  • Adding validation to the constructor to ensure that the initial salary is also valid.
  • Implementing more complex validation logic in the `setSalary()` method, such as checking that the new salary is within a reasonable range.
  • Adding logging or auditing to track changes to the salary.
  • Using immutable objects where appropriate (e.g., the employee ID might be immutable).

FAQ

  • What happens if I try to access a private field from outside the class?

    You will get a compilation error. Private fields can only be accessed from within the class in which they are declared.
  • Why is it important to validate data in setter methods?

    Validating data in setter methods helps to ensure data integrity and prevent errors caused by invalid data. It also makes the code more robust and reliable.