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
Further Enhancements
This `Employee` class could be further enhanced by:
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.